Dev HelpersOpen library
← Back

Copy a file safely in a temp directory

Copy a file safely in a temp directory. A self-contained example using the Python standard library.

Open this example in the interactive library

Source code

from pathlib import Path
from tempfile import TemporaryDirectory
import shutil
with TemporaryDirectory() as folder:
    source = Path(folder) / 'a.txt'
    source.write_text('sample')
    target = Path(folder) / 'b.txt'
    shutil.copy2(source, target)
    print(target.read_text())

Sample output

sample