Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Read second column from file

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?

like image 695
user1251265 Avatar asked Jun 20 '12 01:06

user1251265


People also ask

How do I read a column from a file in Python?

Python3. In this method we will import the csv library and open the file in reading mode, then we will use the DictReader() function to read the data of the CSV file. This function is like a regular reader, but it maps the information to a dictionary whose keys are given by the column names and all the values as keys.


2 Answers

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.

like image 115
Levon Avatar answered Oct 27 '22 17:10

Levon


You could do something like this. Separator is the character your file uses to separate colums, e.g. tabs or commas.

for line in open("inputfile.txt"):
    columns = line.split(separator)
    if len(columns) >= 2:
        print columns[1]
like image 28
Junuxx Avatar answered Oct 27 '22 15:10

Junuxx