我不明白为什么我在循环写入的日志文件中只得到单词和 ln 的第一个匹配项(有 50 个或更多匹配项)。而且它的结构不像我在屏幕上打印时那样好。下面是代码。谢谢!
我正在编写的文件中的结果:343438363939 70642
regex = re.compile(r'(?:3\d){6}')
for root,dirname, files in os.walk(directory):
for file in files:
if file.endswith(".log") or file.endswith(".txt"):
f = open(os.path.join(root,file))
for i, line in enumerate(f.readlines()):
searchedstr = regex.findall(line)
ln = str(i)
for word in searchedstr:
print "\nString found: " + word
print "Line: " + ln
print "File: " + os.path.join(root,file)
print " "
logfile = open('result3.log', 'w')
logfile.write(word + '\n' + ln)
logfile.close()
f.close()
请您参考如下方法:
这是你的问题:
logfile = open('result3.log', 'w')
logfile.write(word + '\n' + ln)
logfile.close()
每次你像这样打开日志文件时,它会删除之前的所有内容 从文件的开头 开始写入。您可以将 open 更改为
logfile = open('result3.log', 'a')
('a' 代表 'append'),或者 - 更好 - 在最外层循环之外只打开一次 logfile,如下所示:
regex = re.compile(r'(?:3\d){6}')
with open('result3.log', 'w') as logfile:
for root, dirname, files in os.walk(directory):
# ...
logfile.write(word + '\n' + ln)
with 负责为您关闭文件,因此您不需要显式的 logfile.close()。 (最好也使用 with 打开 f,如果这样的话 f.close() 不会悬空在嵌套循环下面。)(进一步的附录:enumerate(f.readlines()) 与 enumerate(f) 相同,只是速度较慢。)
