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

标签 python

我目前的代码是

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/

相关文章:

python - 如何从 python 列表中任何特定索引处的句子中提取特定字符串?

python - 如何使用标志仅返回一组使用 findall- Python

python - 生成具有预定义模数和指数的公钥

shell 命令上的 Python 复杂字符串插值

python - 将 python xgboost dMatrix 转换为 numpy ndarray 或 pandas DataFrame

python - 使用 python 子进程将文件从 .sam 转换为 .bam

python - Celery:为什么从接受任务到开始执行有几秒的时间间隔?

Python查找文件中的最后一次出现

python - Py2app/Pygame错误: Library not loaded

python - 在循环中创建子列表