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}")

 

You will almost always want to also use os.path.dirname and os.makedirs to create the destination directory if it does not exist.

#!/usr/bin/python3
import os
import shutil

src = "/path/to/example.txt"
dst = "/tmp/example.txt"

dirname = os.path.dirname(dst)

if os.path.exists(dirname):
  print(f"Directory {dirname} already exists")
else:
  try:
    os.makedirs(dirname)
  except Exception as exception:
    print(f"got the following exception when attempting os.makedirs({dirname}) - {exception}")
  else:
    print(f"successfully created directory {dirname}")

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 f9ffe2 in the box below so that we can be sure you are a human.