I have written a code which opens multiple files in a directory and prints only the first instance of match of required text from each file as output.
Now I want this output in a file. Doing it simply by putting print >> file.txt,... or .write or csv.write inside loop will not serve the purpose.
My code is:
import re, os, csv, sys
path = "D:\\"
in_files = os.listdir(path)
moldesc = ['Match1', 'Match2']
for f in in_files:
file = os.path.join(path, f)
text = open(file, "r")
for line in text:
if moldesc[0] in line:
Text1 = line.split()[-1]
if moldesc[1] in line:
Text2 = line.split()[-1]
print f, Text1, Text2 # I WANT THIS OUTPUT IN A FILE
break
text.close()
print "We are extraction done !!!"
print >> output, "some text",outputshould be an open file (or other file-like object), not a filename.NameErrorifmoldesc[1] in lineis true andmoldesc[0] in lineisn't... (The first time at least - otherwise, it may be Text1 is set from a line that's completely got nothing to do with the line that Text2 is being set for... [eg - subtly incorrect results)) Also, it doesn't seem to matter what match you get, you're always taking the last word from the line? You might as well just haveif any(m in line for m in ['Match1', 'Match2']): ...