Python 文件关闭后不释放文件

Python doesn't release file after it is closed

我需要做的是在.txt 文件上写一些消息,关闭它并发送到服务器。这是在无限循环中发生的,因此代码应该大致如下所示:

from requests_toolbelt.multipart.encoder import MultipartEncoder

num = 0
while True:
    num += 1
    filename = f"example{num}.txt"
    with open(filename, "w") as f:
        f.write("Hello")
        f.close()

    mp_encoder = MultipartEncoder(
                fields={
                    'file': ("file", open(filename, 'rb'), 'text/plain')
                }
            )

    r = requests.post("my_url/save_file", data=mp_encoder, headers=my_headers)
    time.sleep(10)

如果文件是在我的工作目录中手动创建的,post 会起作用,但如果我尝试创建它并通过代码写入,我会收到此响应消息:

500 - Internal Server Error
System.IO.IOException: Unexpected end of Stream, the content may have already been read by another component. 

我没有看到文件出现在 PyCharm 的项目 window 中...我什至使用了 time.sleep(10) 因为起初,我认为这可能是一个时间-相关问题,但我没有解决问题。事实上,只有当我停止代码时,该文件才会出现在我的工作目录中,因此即使在我明确调用 f.close() 之后,该文件似乎仍由程序保留:我知道 with 函数应该负责关闭文件,但它看起来不像那样,所以我尝试添加一个 close() 来了解这是否是问题所在(剧透:不是)

首先,你能不能把open(f, 'rb')改成open("example.txt", 'rb')。在 open 中,您应该传递文件名而不是已关闭的文件指针。

此外,您可以使用os.path.abspath显示位置以了解写入文件的位置。

import os

os.path.abspath('.')

第三点,当你使用with上下文管理器打开文件时,你不会关闭文件。上下文管理器应该这样做。

with open("example.txt", "w") as f:
    f.write("Hello")

我用另一个文件解决了这个问题

with open(filename, "r") as firstfile, open("new.txt", "a+") as secondfile:
        secondfile.write(firstfile.read())
with open(filename, 'w'):
    pass

r = requests.post("my_url/save_file", data=mp_encoder, headers=my_headers)
if r.status_code == requests.codes.ok:
    os.remove("new.txt")
else:
    print("File not saved")

我复制了一份文件,清空原文件保存space并将副本发送到服务器(然后删除副本)。看起来问题是原始文件被 Python 日志记录模块

保持打开状态