繁体   English   中英

python 临时文件 | NamedTemporaryFile 不能使用生成的临时文件

[英]python tempfile | NamedTemporaryFile can't use generated tempfile

我想加载临时文件以进行更改或只是能够将其上传到某处,当我尝试这样做时 - 它会引发错误,如下所示

我已将权限设置为 w+ - 理想情况下应该允许我读写,不确定我在这里缺少什么 - 任何帮助将不胜感激 - 谢谢

>>> from openpyxl import load_workbook
>>> from tempfile import NamedTemporaryFile
>>> import os                     
>>> with NamedTemporaryFile(suffix=".xlsx", mode='w+', delete=True) as tmp:
...     temp_path = tmp.name                
...     os.path.exists(temp_path)           
...     wb = load_workbook(temp_path)       
... 
True
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
  File "C:\Users\my_name\VS_PROJECTS\.venv\lib\site-packages\openpyxl\reader\excel.py", line 315, in load_workbook
    reader = ExcelReader(filename, read_only, keep_vba,
  File "C:\Users\my_name\VS_PROJECTS\.venv\lib\site-packages\openpyxl\reader\excel.py", line 124, in __init__
    self.archive = _validate_archive(fn)
  File "C:\Users\my_name\VS_PROJECTS\.venv\lib\site-packages\openpyxl\reader\excel.py", line 96, in _validate_archive
    archive = ZipFile(filename, 'r')
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.2288.0_x64__qbz5n2kfra8p0\lib\zipfile.py", line 1251, in __init__
    self.fp = io.open(file, filemode)
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\my_name\\AppData\\Local\\Temp\\tmp5dsrqegj.xlsx'

显然,您在 Windows 上。

On Windows, you can't open another handle to a O_TEMPORARY file while it's still open (see eg https://github.com/bravoserver/bravo/issues/111 , https://docs.python.org/3/library /tempfile.html#tempfile.NamedTemporaryFile,https://bugs.python.org/issue14243

您需要使用delete=False并手动清理,例如

try:
    with NamedTemporaryFile(suffix=".xlsx", mode='w+', delete=True) as tmp:
       temp_name = fp.name
       # ...
finally:
    try:
        os.unlink(temp_name)
    except Exception:
        pass

我正在使用这个助手包装 AKX 的解决方案:

class WritableTempFile:
    """
    Avoid "Permission denied error" on Windows:
      with tempfile.NamedTemporaryFile("w", suffix=".gv") as temp_file:
        # Not writable on Windows:
        # https://docs.python.org/3/library/tempfile.html#tempfile.NamedTemporaryFile

    Example:
        with WritableTempFile("w", suffix=".gv") as temp_file:
            tree.to_dotfile(temp_file.name)
    """

    def __init__(self, mode="w", *, encoding=None, suffix=None):
        self.mode = mode
        self.encoding = encoding
        self.suffix = suffix

    def __enter__(self):
        self.temp_file = tempfile.NamedTemporaryFile(
            self.mode, encoding=self.encoding, suffix=self.suffix, delete=False
        )
        return self.temp_file

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.temp_file.close()
        os.unlink(self.temp_file.name)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM