4

I would like to load the temp file to make changes or just be able to upload it somewhere, When I try to do so - It throws an error as shown below

I have set the permission to w+ - which should ideally allow me to read and write, Not sure what am I missing here - Any help would be appreciated - thanks

>>> 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'
Mike730
  • 495
  • 1
  • 5
  • 14
  • this post may help https://stackoverflow.com/q/36434764/13273054 – kiranr Mar 22 '21 at 10:49
  • 1
    Apart from the permssions problem, this won't work as openpyxl won't be able to read an empty file. – Charlie Clark Mar 22 '21 at 11:35
  • @CharlieClark I agree, I already tried to use workbook and save file ``` ... temp_path = tmp.name + '.xlsx' ... os.path.exists(temp_path) ... wb = Workbook() ... wb.save(temp_path) ``` – Mike730 Mar 22 '21 at 11:38

2 Answers2

2

You're on Windows, evidently.

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

You'll need to use delete=False and clean up manually, e.g.

try:
    tmp = NamedTemporaryFile(suffix=".xlsx", mode='w+', delete=False)
    tmp.close()
    temp_name = tmp.name
    os.path.exists(temp_path)           
    wb = load_workbook(temp_path)
finally:
    try:
        os.unlink(temp_name)
    except Exception:
        pass
puf
  • 359
  • 3
  • 13
AKX
  • 152,115
  • 15
  • 115
  • 172
0

I am using this helper to wrap AKX's solution:

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)
mar10
  • 14,320
  • 5
  • 39
  • 64