Python - reading second column from file

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

+7
source share
4 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 spaces.

The split () function can specify different delimiters. For example, if the columns were separated by commas , you would use line.split(',') in the above code.

NOTE. Using with to open a file automatically closes it when you are finished, or if you encounter an exception.

+11
source

You could do something like this. Separator - a character used by your file to separate columns, for example. tabs or commas.

 for line in open("inputfile.txt"): columns = line.split(separator) if len(columns) >= 2: print columns[1] 
+7
source

Fast n dirty

If AWK is installed:

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

Class usage

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 looks like this:

  hel lo wor ld
 wor ld hel lo

You will receive the following:

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

Additional notes

  • You can use pyawk for more awk features.
  • If you use the Quick method, use subprocess.Popen
  • You can change the delimiter getCol('inputdata1.txt', delim=", ")
  • Use filter to remove empty values ​​or uncomment pass
+5
source
 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 the columns of each row.

0
source

All Articles