In issue14243 [1] there are two issues being tracked:
- the difference in opening shared files between posix and Windows
- the behavior of closing the underlying file in the middle of
NamedTemporaryFile's context management
I'd like to address and get feedback on the context management issue.
```python
from tempfile import NamedTemporaryFile
with NamedTemporaryFile() as fp:
fp.write(b'some data’)
fp.flush(). # needed to ensure data is actually in the file ;-)
fp = open(fp.name())
data = fp.read()
assert data == 'some_data'
```
I generally use a slightly different pattern for this:
with NamedTemporaryFile() as fp:
fp.write(b'some data’)
fp.flush()
fp.seek(0)
data = fp.read()
That is, reuse the same “fp” and just reset the stream. An advantage of this approach is that you don’t need a named temporary file for this (and could even use a spooled one). That said, I at times use this pattern with a named temporary file with a quick self-test for the file contents before handing of the file name to an external proces.