Bootstrap FreeKB - Python (Scripting) - Copy file using shutil
Python (Scripting) - Copy file using shutil

Updated:   |  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 Buy Me A Coffee



Comments


Add a Comment


Please enter c92d7b in the box below so that we can be sure you are a human.