【问题标题】:file.write(line) not writing all of the lines in the filefile.write(line) 没有写入文件中的所有行
【发布时间】:2017-03-30 10:39:06
【问题描述】:

我有下面的代码来检查目录中的 .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")

【问题讨论】:

    标签: python python-2.7 tkinter


    【解决方案1】:

    问题出在:file = open("out.txt", "w") 您打开 out.txt 进行写作的地方。文件内容被删除。

    改用file = open("out.txt", "a"),该文件将被打开以附加先前写入的内容。

    python documentation中所述:

    • 'w' 仅用于写入(现有的同名文件将被删除)
    • 'a' 打开文件进行追加;写入文件的任何数据都会自动添加到末尾

    附:不要忘记调用 file.close()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-08
      • 1970-01-01
      • 1970-01-01
      • 2021-11-29
      • 1970-01-01
      • 1970-01-01
      • 2016-05-25
      相关资源
      最近更新 更多