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]