python - AttributeError: FileInput instance has no attribute '__exit__' -


i trying read multiple input files , print second row each file next each other table

import sys import fileinput  fileinput.input(files=('cutflow_ttjets_1l.txt ', 'cutflow_ttjets_1l.txt ')) f:     line in f:         proc(line)    def proc(line):      parts = line.split("&") # split line parts      if  "&" in line:    # if @ least 2 parts/columns          print parts[1] # print column 2  

but "attributeerror: fileinput instance has no attribute '__exit__'"

the problem of python 2.7.10, fileinput module not support being used context manager, i.e. with statement, have handle closing sequence yourself. following should work:

f = fileinput.input(files=('cutflow_ttjets_1l.txt ', 'cutflow_ttjets_1l.txt '))  line in f:     proc(line)  f.close() 

note in recent versions of python 3, can use module context manager.


for second part of question, assuming each file formatted equal number of data lines of form xxxxxx & xxxxx, 1 can make table of data second column of each data follows:

start empty list table rows lists of second column entries each file:

table = [] 

now iterate on lines in fileinput sequence, using fileinput.isfirstline() check if @ new file , make new row:

for line in f:     if fileinput.isfirstline():         row = []         table.append(row)     parts = line.split('&')     if len(parts) > 1:         row.append(parts[1].strip())  f.close()                       

now table transpose of want, each row containing second column entries of given line of each file. transpose list, 1 can use zip , loop on rows transposed table, using join string method print each row comma separator (or whatever separator want):

for row in zip(*table):     print(', '.join(row))                              

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -