# Creation of a temp file on Windows

I implemented a test that reads data from temp file on Windows.
I originally had an issue that I solved with the help of this answer

def test_read(self):
import tempfile
import os
try:
with tempfile.NamedTemporaryFile(delete=False) as temp:
content = 'Some data'
temp.write(content.encode('utf-8'))
temp.flush()
finally:
os.remove(temp.name)


How can I do this better?
Is it ok to have try...finally in the test?

b is a custom module. It reads data from temp file.

def read(path):
if path in VIRTUAL_FS:
return VIRTUAL_FS[path]
with open(path.as_posix(), 'r') as file:

• What is b? What is the purpose of this test? – 200_success Sep 15 '14 at 15:43
• Purpose that b reads data from file properly. – drets Sep 15 '14 at 15:59

In the try block, temp might not get assigned, so temp.name would be an error. But this is an extremely unlikely scenario.

You seem to be going out of your way to defeat the natural clean-up capability of the named temporary file:

If delete is true (the default), the file is deleted as soon as it is closed.

Since the file is opened via a with block, it should be closed automatically at the end of the block, and automatically deleted as well, if you let it. Therefore, you shouldn't need the try...finally at all, and you can remove the delete=False parameter from NamedTemporaryFile:

def test_read(self):
import tempfile

with tempfile.NamedTemporaryFile() as temp:
content = 'Some data'
temp.write(content.encode('utf-8'))
temp.flush()

When you open a file for reading, you can omit the r in here:
with open(path.as_posix(), 'r') as file:

Finally, b is terrible name. It doesn't tell anything about the module.
• Thanks, it's good to know the default mode for open function. On the other hand if I would remove the delete=False and run it on Windows, I get permission denied IOError as in this question. – drets Sep 15 '14 at 21:30