首页 > 解决方案 > Python 关闭后不释放文件

问题描述

我需要做的是在 .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)

如果文件是在我的工作目录中手动创建的,则该帖子有效,但如果我尝试创建它并通过代码在其上写入,我会收到以下响应消息:

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

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

标签: pythonfilehttp-status-code-500

解决方案


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

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")

我制作了文件的副本,清空原始文件以节省空间并将副本发送到服务器(然后删除副本)。看起来问题是原始文件被 Python 日志记录模块保持打开状态


推荐阅读