Reading specific columns from a text file in python

前端 未结 6 565
一生所求
一生所求 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:52

    You have a space delimited file, so use the module designed for reading delimited values files, csv.

    import csv
    
    with open('path/to/file.txt') as inf:
        reader = csv.reader(inf, delimiter=" ")
        second_col = list(zip(*reader))[1]
        # In Python2, you can omit the `list(...)` cast
    

    The zip(*iterable) pattern is useful for converting rows to columns or vice versa. If you're reading a file row-wise...

    >>> testdata = [[1, 2, 3],
                    [4, 5, 6],
                    [7, 8, 9]]
    
    >>> for line in testdata:
    ...     print(line)
    
    [1, 2, 3]
    [4, 5, 6]
    [7, 8, 9]
    

    ...but need columns, you can pass each row to the zip function

    >>> testdata_columns = zip(*testdata)
    # this is equivalent to zip([1,2,3], [4,5,6], [7,8,9])
    
    >>> for line in testdata_columns:
    ...     print(line)
    
    [1, 4, 7]
    [2, 5, 8]
    [3, 6, 9]
    

提交回复
热议问题