Reading specific columns from a text file in python

Jethro picture Jethro · May 13, 2015 · Viewed 164.2k times · Source

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

if for example I want the numbers contained only in the second column, how do i extract that column into a list?

Answer

ForceBru picture ForceBru · May 13, 2015
f=open(file,"r")
lines=f.readlines()
result=[]
for x in lines:
    result.append(x.split(' ')[1])
f.close()

You can do the same using a list comprehension

print([x.split(' ')[1] for x in open(file).readlines()])

Docs on split()

string.split(s[, sep[, maxsplit]])

Return a list of the words of the string s. If the optional second argument sep is absent or None, the words are separated by arbitrary strings of whitespace characters (space, tab, newline, return, formfeed). If the second argument sep is present and not None, it specifies a string to be used as the word separator. The returned list will then have one more item than the number of non-overlapping occurrences of the separator in the string.

So, you can omit the space I used and do just x.split() but this will also remove tabs and newlines, be aware of that.