user1251265
user1251265

Reputation: 89

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?

Upvotes: 8

Views: 58998

Answers (4)

Youssef Tamaaz
Youssef Tamaaz

Reputation: 1

f = open("file_to_read.txt") # open your file

line = f.readline().strip() # get the first line in line

while line: # while a line exists in the file f
    columns = line.split('separator') # get all the columns
    while columns: # while a column exists in the line
        print columns # print the column
    line = f.readline().strip() # get the next line if it exists

With this code, you have access to all columns of each line.

Upvotes: 0

Mehdi Nellen
Mehdi Nellen

Reputation: 8964

Quick 'n dirty

If AWK is installed:

# $2 for the second column
os.system("awk '{print $2}' inputdata1.txt")

Using a class

Make a class:

class getCol:
    matrix = []
    def __init__(self, file, delim=" "):
        with open(file, 'rU') as f:
            getCol.matrix =  [filter(None, l.split(delim)) for l in f]

    def __getitem__ (self, key):
        column = []
        for row in getCol.matrix:
            try:
                column.append(row[key])
            except IndexError:
                # pass
                column.append("")
        return column

If inputdata1.txt would look like:

hel   lo   wor   ld
wor   ld   hel   lo

You would get this:

print getCol('inputdata1.txt')[1]
#['lo', 'ld']

Additional notes

  • You can use pyawk for more awk features
  • If you're using the Quick 'n dirty method use subprocess.Popen
  • You can change the delimiter getCol('inputdata1.txt', delim=", ")
  • Use filter to remove empty values or uncomment pass

Upvotes: 5

Levon
Levon

Reputation: 143022

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.

Upvotes: 13

Junuxx
Junuxx

Reputation: 14261

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]

Upvotes: 8

Related Questions