gpt4 book ai didi

Python os.remove(filename) 抛出错误 "already being used by temp"

转载 作者:行者123 更新时间:2023-12-03 20:51:23 26 4
gpt4 key购买 nike

我目前的代码是

import os
import pickle
import tempfile

# Pickle on HIGHEST_PROTOCOL breaks on Python 3.6.5
_PICKLE_PROTOCOL = 4
#CHANGED FROM 2 TO 4 TO ACCOMODATE VERSION, DONE BY USER


def _pickle_iterable(filename, iterable):
with open(filename, 'wb') as pickle_fh:
pklr = pickle.Pickler(pickle_fh, _PICKLE_PROTOCOL)
for entry in iterable:
pklr.dump(entry)
pklr.clear_memo()


def _open_pickle(filename):
return open(filename, 'rb')


def _unpickle_iterable(pickle_fh):
with pickle_fh:
unpklr = pickle.Unpickler(pickle_fh)
try:
while True:
yield unpklr.load()
except EOFError:
pass


def file_buffered_tee(iterable, n=2):
_, filename = tempfile.mkstemp()
try:
_pickle_iterable(filename, iterable)
return tuple(_unpickle_iterable(_open_pickle(filename)) for _ in range(n))
finally:
os.remove(filename)
os.remove(filename) 给出错误
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\s%username%\\AppData\\Local\\Temp\\tmpaoos53ie'
我不知道如何修复它,我从中提取的 GitHub 存储库已存档,我无法打开另一个问题请求。
我要回到 stackoverflow,在我见过的其他任何地方我都找不到适用的答案,虽然我认为我理解代码,但我一直遇到错误,哈哈
任何帮助表示赞赏!谢谢!
编辑 1:忘记导入...愚蠢的错误
编辑 2:我省略了代码,因为我认为它不需要。谢谢大家的耐心 :P
编辑3:回溯:
line37, in file_buffered_tee:

os.remove(filename)

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\%username%\\AppData\\Local\\Temp\\tmp*xxxxxxx*'
编辑 4: 显然同样的问题正在发生 here ,但是它完成了答案所说的所有事情,但返回了相同的错误......仍然没有在这里回答并且仍然很困惑。文档也没有帮助

最佳答案

您可以告诉 tempfile 在关闭时删除文件。这样,当您关闭文件时,该文件将被自动删除。
这可能对您有帮助:https://docs.python.org/3/library/tempfile.html
tempfile.NamedTemporaryFile(mode='w+b', buffering=None, encoding=None, newline=None, suffix=None, prefix=None, dir=None, delete=True , *, errors=没有任何)
delete=True 参数就是你要找的。现在使用 tempfile 通过 file.close() 关闭文件

关于Python os.remove(filename) 抛出错误 "already being used by temp",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62618319/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com