python - 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() 来了解这是否是问题(剧透:不是)
解决方案
我通过使用另一个文件解决了这个问题
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 日志记录模块保持打开状态
推荐阅读
- ffmpeg - 使用 ffmpeg 将文本和图像添加到视频中
- javascript - Angular 6 - HTTP 响应/变量篡改
- android - Firebase 云消息传递:FCM 令牌过期
- autodesk-forge - MAX 到 SVF 导致审美问题
- airflow - 在 Airflow DAG 中生成要单独处理的多个任务
- kubernetes - ServiceAccount 机密在 OpenTelekomCloud 的 ClusterContainerEngine 中以限制性权限挂载
- ruby-on-rails - 如何通过 URL_path 传递值并在 Rails 的目标页面中检索它
- python-3.x - 如果发现重复的文件名,发出警报并停止脚本
- json - 使用内部属性合并数组
- angular - 在 Angular 的 http 订阅操作中使用 ngx-spinner