You have a space delimited file, so use a module designed to read value delimited csv , csv .
import csv with open('path/to/file.txt') as inf: reader = csv.reader(inf, delimiter=" ") second_col = list(zip(*reader))[1]
The zip(*iterable) is useful for converting rows to columns or vice versa. If you read the file line by line ...
>>> 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]
Adam smith
source share