【问题标题】:How to write text to temp file?如何将文本写入临时文件?
【发布时间】:2021-12-08 16:43:21
【问题描述】:

我正在尝试将一些文本写入临时文件,但由于某种原因它不起作用。当我打印print(tmp.readlines()) 时,我只得到一个空列表。

如您所见,我首先循环遍历sentences.txt,并将每个与"I like cars." 不匹配的句子写入 tmp 文件。然后我想把那些句子写回sentences.txt,所以我基本上是在过滤sentences.txt文件。

with open("sentences.txt") as file:
    with tempfile.NamedTemporaryFile(mode="w+") as tmp:
        for line in file:
            if line.rstrip() != "I like cars.":
                tmp.write(line + "\n")
        with open("sentences.txt", "a") as f:
            for line in tmp:
                f.write(line + "\n")

【问题讨论】:

    标签: python list file for-loop temporary-files


    【解决方案1】:

    这里的问题是您正在写入一个文件,然后尝试从同一个文件中读取。您需要在 for line in tmp 之前有 tmp.seek(0) 才能将文件指针 (tmp) 重置到文件的开头

    【讨论】:

    • 但问题是tmp.write()不起作用。
    • @Nicke7117 你怎么确定tmp.write() 不起作用?正如我在回答中所说,您需要有 tmp.seek(0) 才能从您写入内容的同一文件中读取。我更新了我的答案是f.seek,但应该是tmp.seek
    猜你喜欢
    • 2013-12-06
    • 2017-06-19
    • 2012-10-27
    • 2010-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多