简体   繁体   English

file.write(line)不写文件中的所有行

[英]file.write(line) not writing all of the lines in the file

I have the code below to check whether .txt files in a directory contain words from a chosen word list, it also prints to the console and writes the results to the out.txt file. 我有下面的代码来检查目录中的.txt文件是否包含所选单词列表中的单词,它还会打印到控制台并将结果写入out.txt文件。 However when there is more than one .txt file in the directory it only writes the last one checked to the out.txt file instead of all of them. 但是,当目录中有多个.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")

The problem is in line: file = open("out.txt", "w") where you open out.txt for writing. 问题所在是: file = open("out.txt", "w") ,您在其中打开out.txt进行写入。 The content of the file is erased. 文件内容被删除。

Use file = open("out.txt", "a") instead and the file will be opened for appending the previously written content. 使用file = open("out.txt", "a")代替,该文件将被打开以附加先前编写的内容。

As stated in python documentation : python文档中所述

  • 'w' for only writing (an existing file with the same name will be erased) 'w'仅用于写入(具有相同名称的现有文件将被删除)
  • 'a' opens the file for appending; 'a'打开文件进行追加; any data written to the file is automatically added to the end 写入文件的所有数据都会自动添加到末尾

Ps Don't forget to call file.close() Ps不要忘记调用file.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM