My Code Image队 我的任务是在所有文件中找到一个字符串,并将文件名,文件路径和搜索的字符串写在另一个文件的一行中。所以,我实现了它根据需要打印输出到stdout。但是,我无法将其指向新文件。当我将输出定向到新文件时,我只获得最后的文件结果,而不是所有以前文件的搜索结果。可能是我没有正确打开/关闭文件这里是代码:
结果文件仅显示最后的文件搜索参数,而不显示其余文件。我希望resut文件包含每个文件的条目。
resultsFile = "results.txt"
wf = open(search_path + resultsFile, 'w')
while line != '':
# Search for string in line
index = line.find(search_str)
if index != -1:
print(fname, "[", line_no, ",", index, "] ", line, sep="")
wf.write(fname + " " + str(search_path) + str(search_string) + " ")
# Read next line
line = fo.readline()
STDOUT上的输出:
file1 z:/dir1/file1.json String
file2 z:/dir1/file2.json String
..
..
file10 z:/dir1/file10.json String
输出结果文件中的:
file10 z:/dir1/file10.json String
答案 0 :(得分:0)
您正在使用“写入”模式反复覆盖结果文件。
wf = open(search_path + resultsFile, 'w')
将附加模式替换为:
wf = open(search_path + resultsFile, 'a')
答案 1 :(得分:0)
我不得不重新启动我的pycharm编辑器并开始看到附加模式工作。
但我还需要了解优化的解决方案。
我可以写一个列表然后最终将该列表写入文件吗?那是最佳的吗?