Well this works:
from tempfile import NamedTemporaryFile
import os
with NamedTemporaryFile(delete=False) as fp:
fp.write(b'some data')
fp.close()
with open(fp.name, 'rb') as fp2:
data = fp2.read()
os.remove(fp.name)
assert data == b'some data'
Of course it is theoretically possible that another app will do
something to the temporary file between the "fp.close()" and the "open"
on the next line, or between closing fp2 and the "os.remove". Is this a
concern?
Rob Cliffe
On 08/04/2021 22:42, Ethan Furman wrote:
On 4/8/21 1:43 PM, Antoine Pitrou wrote:
On Thu, 8 Apr 2021 13:31:26 -0700
Ethan Furman <et...@stoneleaf.us> wrote:
```python
from tempfile import NamedTemporaryFile
with NamedTemporaryFile() as fp:
fp.write(b'some data')
fp.close() # Windows workaround
fp.open()
data = fp.read()
assert data == 'some_data'
```
The problem is that, even though `fp.open()` is still inside the
context manager, the `close()` call deletes the file
[2]. To handle this scenario, my proposal is two-fold:
1) stop using the TEMPFILE OS attribute so the OS doesn't delete the
file on close
2) add `.open()` to NamedTemporaryFile
Instead, you could add a dedicated `.reopen()`?
The main hurdle is that on Windows we let the OS manage the lifetime
of the file, which means that it is deleted as soon as it is closed.
We would need to remove that branch and treat all NamedTemporaryFiles
the same.
We could add reopen(), but since close() is already there... although
I do like the name of `reopen`.
--
~Ethan~
_______________________________________________
Python-Dev mailing list -- python-dev@python.org
To unsubscribe send an email to python-dev-le...@python.org
https://mail.python.org/mailman3/lists/python-dev.python.org/
Message archived at
https://mail.python.org/archives/list/python-dev@python.org/message/2DGIFUS6SU56MP6OWOEJPSWEDR2PL5CS/
Code of Conduct: http://python.org/psf/codeofconduct/
_______________________________________________
Python-Dev mailing list -- python-dev@python.org
To unsubscribe send an email to python-dev-le...@python.org
https://mail.python.org/mailman3/lists/python-dev.python.org/
Message archived at
https://mail.python.org/archives/list/python-dev@python.org/message/5E5PTFW2BXU33V7LGVKMRD5I2425OT6G/
Code of Conduct: http://python.org/psf/codeofconduct/