Empty/blank result file when using shutil to copy a tempfile

Question:

import tempfile
import shutil
tmp_f = tempfile.NamedTemporaryFile(delete=False)
tmp_f.write("hello world")
shutil.copy(tmp_f.name, "/etc/exports")

When I read /etc/exports, it is a completely empty file. what is wrong?

Asked By: pepero

||

Answers:

You need to close the file:

tmp_f.write("hello world")
tmp_f.close()
Answered By: j4hangir

In addition to closing the file, it You can use .flush() to write the buffer to disk. This may be beneficial in cases when you want to move the file after writing to it, but also want to take advantage of a context manager and delete=True (the default mode) to automatically clean up the temp file. For example:

import os
import shutil
import tempfile

destination_path = "hello.txt"
content = "hello world"

with tempfile.NamedTemporaryFile() as temp:
    temp.write(content.encode("utf-8"))
    temp.flush()
    shutil.copy(temp.name, destination_path)

with open(destination_path) as f:
    print(f.read())

os.remove(destination_path)
Answered By: ggorlen
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.