Python (Scripting) - Copy file using shutil
by
Jeremy Canfield |
Updated: April 01 2024
| Python (Scripting) articles
shutil.copyfile can be used to copy a local file from one location to another location on the system the Python script is running on. Here is the minimal boilterplate code without error handling.
#!/usr/bin/python3
import shutil
src = "/path/to/example.txt"
dst = "/tmp/example.txt"
shutil.copyfile(src, dst)
Here is a more practical example, with try/except/else error handling.
#!/usr/bin/python3
import shutil
src = "/path/to/example.txt"
dst = "/tmp/example.txt"
try:
shutil.copyfile(src, dst)
except Exception as exception:
print(f"Got the following exception when attempting to copy {src} to {dst}: {exception}")
else:
print(f"Successfully copied {src} to {dst}")
Did you find this article helpful?
If so, consider buying me a coffee over at