Copy and replace files in Python

Python | copy and replace files (Example of shutil module): Here, we are going to learn about the shutil module in Python – which is used for high-level file operations. Submitted by Sapna Deraje Radhakrishna, on September 30, 2019

Python shutil Module

The python language provides a built-in module "shutil", which offers numerous high-level operations on files and collections of files. In particular, functions are provided to support the file copying and removal.

Copy file

The shutil.copyfile() method is used for copying files in Python. It copies the contents of file from source(src) to destination(dst). src and dst are the path names as a string. dst must be the complete target file name.

shutil.copyfile(src, dst, *, follow_symlinks=True)


  • If src and dst are the same locations, SameFileError is raised.
  • The dst must be writable, else an IO Error will be raised.
  • If dst already exists, it will be replaced.
  • If follow_symlinks are false and src is a symbolic link, then a new symbolic link will be created instead of copying the file src points to.

Python program to copy the files using shutil.copyfile()

# importing the modules
import os
import shutil

# getting the current working directory
src_dir = os.getcwd()

# printing current directory

# copying the files
shutil.copyfile('test.txt', 'test.txt.copy2') #copy src to dst

# printing the list of new files


['python_samples', 'test.txt', 'test', 'test.txt.copy', 'test.txt.copy2']

Move files

The shutil.move() method is used for moving files in Python. It recursively moves the file from src to dst and returns the destination. Consider the below-given syntax:

shutil.move(src, dst, copy_function=copy2)


  • If the destination is an existing directory, then the src object is moved inside the given dst.
  • In case the destination already exists and is not a directory, it will be overwritten using os.rename().
  • In case the destination is on the current filesystem, then os.rename() is used. In the case of symlinks, a new symlink pointing to the target of src will be created in or as dst and src will be removed.
  • The default copy_function is copy2(). Using copy() as the copy_function allows the move to succeed.

Python program to move files

Commnd to get the list of files and directories:

-bash-4.2$ ls
python_samples  test  test.txt  test.txt.copy  test.txt.copy2


# Importing the modules
import os
import shutil

# getting src & dest directories
src_dir = os.getcwd() #gets the current working dir
dest_dir = src_dir + "/python_samples" 

# move method to move the file

# the file 'test.txt' is moved from src to dest

# list of files in dest


['python_samples', 'test', 'test.txt.copy', 'test.txt.copy2']
['.git', '.gitignore', '', 'src', 'test.txt']


Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.