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
JavaScript
x
21
21
1
>>> from openpyxl import load_workbook
2
>>> from tempfile import NamedTemporaryFile
3
>>> import os
4
>>> with NamedTemporaryFile(suffix=".xlsx", mode='w+', delete=True) as tmp:
5
temp_path = tmp.name
6
os.path.exists(temp_path)
7
wb = load_workbook(temp_path)
8
9
True
10
Traceback (most recent call last):
11
File "<stdin>", line 4, in <module>
12
File "C:Usersmy_nameVS_PROJECTS.venvlibsite-packagesopenpyxlreaderexcel.py", line 315, in load_workbook
13
reader = ExcelReader(filename, read_only, keep_vba,
14
File "C:Usersmy_nameVS_PROJECTS.venvlibsite-packagesopenpyxlreaderexcel.py", line 124, in __init__
15
self.archive = _validate_archive(fn)
16
File "C:Usersmy_nameVS_PROJECTS.venvlibsite-packagesopenpyxlreaderexcel.py", line 96, in _validate_archive
17
archive = ZipFile(filename, 'r')
18
File "C:Program FilesWindowsAppsPythonSoftwareFoundation.Python.3.8_3.8.2288.0_x64__qbz5n2kfra8p0libzipfile.py", line 1251, in __init__
19
self.fp = io.open(file, filemode)
20
PermissionError: [Errno 13] Permission denied: 'C:\Users\my_name\AppData\Local\Temp\tmp5dsrqegj.xlsx'
21
Advertisement
Answer
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.
JavaScript
1
12
12
1
try:
2
tmp = NamedTemporaryFile(suffix=".xlsx", mode='w+', delete=False)
3
tmp.close()
4
temp_name = tmp.name
5
os.path.exists(temp_path)
6
wb = load_workbook(temp_path)
7
finally:
8
try:
9
os.unlink(temp_name)
10
except Exception:
11
pass
12