HiveBrain v1.2.0
Get Started
← Back to all entries
debugpythonMinor

Creation of a temp file on Windows

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
filetempcreationwindows

Problem

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):
"""Test read from file"""
import tempfile
import os
try:
with tempfile.NamedTemporaryFile(delete=False) as temp:
content = 'Some data'
temp.write(content.encode('utf-8'))
temp.flush()
self.assertEqual(content, b.read(Path(temp.name)))
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):
"""Reads file content from FS"""
if path in VIRTUAL_FS:
return VIRTUAL_FS[path]
with open(path.as_posix(), 'r') as file:
return file.read()

Solution

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):
    """Test read from file"""
    import tempfile

    with tempfile.NamedTemporaryFile() as temp:
        content = 'Some data'
        temp.write(content.encode('utf-8'))
        temp.flush()
        self.assertEqual(content, b.read(Path(temp.name)))


When you open a file for reading, you can omit the r in here:

with open(path.as_posix(), 'r') as file:
   return file.read()


Finally, b is terrible name. It doesn't tell anything about the module.

Code Snippets

def test_read(self):
    """Test read from file"""
    import tempfile

    with tempfile.NamedTemporaryFile() as temp:
        content = 'Some data'
        temp.write(content.encode('utf-8'))
        temp.flush()
        self.assertEqual(content, b.read(Path(temp.name)))
with open(path.as_posix(), 'r') as file:
   return file.read()

Context

StackExchange Code Review Q#62955, answer score: 2

Revisions (0)

No revisions yet.