我编写了一个代码,它在一个目录中打开多个文件,并且只打印每个文件中所需文本的第一个匹配实例作为输出。
现在我想要这个输出在一个文件中。简单地通过 put print >> file.txt,...
or .write
or csv.write
inside 循环来做这件事不会达到目的。
我的代码是:
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 !!!"