Skip to content
Advertisement

Copying a NamedTemporaryFile in Linux results in empty file

I am writing some contents to a tempfile.NamedTemporaryFile in Python 3 under Ubuntu 16.04. Under certain circumstances, I want to copy that file to a different location after the writing is done. The problem is reproduced with the following code:

import tempfile
import shutil

with tempfile.NamedTemporaryFile('w+t') as tmp_file:
    print('Hello, world', file=tmp_file)
    shutil.copy2(tmp_file.name, 'mytest.txt')

mytest.txt is empty once the execution is over. If I use delete=False when creating the NamedTemporaryFile I can inspect its content in /tmp/ and they are fine.

I know the file cannot be open again while open under Windows as per the documentation, but Linux should be fine, so I wouldn’t expect it to be that.

What is happening and how can it be resolved?

Advertisement

Answer

The problem is that the print() calls are not being flushed, so when the file is copied nothing has yet been written to it.

Using flush=True as a parameter of print() fixes the issue:

import tempfile
import shutil

with tempfile.NamedTemporaryFile('w+t') as tmp_file:
    print('Hello, world', file=tmp_file, flush=True)
    shutil.copy2(tmp_file.name, 'mytest.txt')
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement