Reading specific columns from a text file in python

前端 未结 6 545
一生所求
一生所求 2020-12-08 05:26

I have a text file which contains a table comprised of numbers e.g:

5 10 6

6 20 1

7 30 4

8 40 3

9 23 1

4 13 6

6条回答
  •  借酒劲吻你
    2020-12-08 05:55

    First of all we open the file and as datafile then we apply .read() method reads the file contents and then we split the data which returns something like: ['5', '10', '6', '6', '20', '1', '7', '30', '4', '8', '40', '3', '9', '23', '1', '4', '13', '6'] and the we applied list slicing on this list to start from the element at index position 1 and skip next 3 elements untill it hits the end of the loop.

    with open("sample.txt", "r") as datafile:
        print datafile.read().split()[1::3]
    

    Output:

    ['10', '20', '30', '40', '23', '13']
    

提交回复
热议问题