我有下面的代码来检查目录中的.txt文件是否包含来自所选单词列表的单词,它还会打印到控制台并将结果写入out.txt文件。但是,当目录中有多个.txt文件时,它只将最后一个文件写入out.txt文件而不是全部文件。
self.wordopp = askdirectory(title="Select chat log directory")
path = self.wordopp
files = os.listdir(path)
paths = []
wordlist = self.wordop
word = open(wordlist)
l = set(w.strip().lower() for w in word)
inchat = []
for file in files:
paths.append(os.path.join(path, file))
with open(paths[-1]) as f:
found = False
file = open("out.txt", "w")
for line in f:
line = line.lower()
if any(w in line for w in l):
found = True
print (line)
file.write(line)
if not found:
print("not here")
答案 0 :(得分:1)
问题在于:file = open("out.txt", "w")
你打开out.txt进行写作。文件的内容将被删除。
改为使用file = open("out.txt", "a")
,将打开该文件以附加以前写入的内容。
如python documentation中所述:
P.S。不要忘记调用file.close()