python shutil copy file code example

Example 1: python copy file

from shutil import copyfile
copyfile(src, dst)

Example 2: shutil copy python

import os
import shutil

source = 'current/test/test.py'
target = '/prod/new'

assert not os.path.isabs(source)
target = os.path.join(target, os.path.dirname(source))

# create the folders if not already exists
os.makedirs(target)

# adding exception handling
try:
    shutil.copy(source, target)
except IOError as e:
    print("Unable to copy file. %s" % e)
except:
    print("Unexpected error:", sys.exc_info())

Example 3: shutil copyfile python

# Source path
source = "/home/User/Documents/file.txt"
  
# Destination path
destination = "/home/User/Documents/file(copy).txt"
  
# Copy the content of
# source to destination
dest = shutil.copyfile(source, destination)