我遇到的问题是,不是将读取文件的所有行都重写到输出中,而是只有最后一行在输出文件中。我相信它被一遍又一遍地写,但我似乎不知道如何修复这个循环。如果有人能帮我,我将不胜感激。这个问题可能与在for循环中重复打开我的文件有关。你知道吗
import os
import re
# 1.walk around directory and find lastjob.txt file in one of folders
rootDir = "C:\\Users\Bob\Desktop\Path Parsing Project"
for path, dirs, files in os.walk(rootDir):
for filename in files:
fullpath = os.path.join(path, filename)
if filename=="text.txt":
# 2.open file. read from file
fi = open(fullpath, 'r')
# 3.parse text in incoming file and use regex to find PATH
for line in fi:
m = re.search("(Adding file.*)",line)
if m:
#4.write path and info to outgoing file
#print(line)
fo = open('outputFile', 'w')
fo.write(line + '\n')
通过将
fo = open('outputFile', 'w')
放在开头,我得到了所需的结果,并且脚本处理速度更快。你知道吗相关问题 更多 >
编程相关推荐