Python - Read second column from file

user1251265 picture user1251265 · Jun 20, 2012 · Viewed 54.5k times · Source

My input file has two columns. I am trying to print the second column of inputdata1.txt within a second for-loop. But my code is not working. Can someone tell me what should I do?

Answer

Levon picture Levon · Jun 20, 2012
with open('inputdata1.txt') as inf:
    for line in inf:
        parts = line.split() # split line into parts
        if len(parts) > 1:   # if at least 2 parts/columns
            print parts[1]   # print column 2

This assumes the columns are separated by whitespace.

Function split() can specify different separators. For instance if the columns were separated with commas , you'd use line.split(',') in the code above.

NOTE: Using with to open your file automatically closes it when you are done, or if you encounter an exception.