Home »
Python
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
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
shutil.copyfile(src, dst, *, follow_symlinks=True)
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.
Reminders,
- 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 code 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
print(src_dir)
# copying the files
shutil.copyfile('test.txt', 'test.txt.copy2') #copy src to dst
# printing the list of new files
print(os.listdir())
Output
/home/sradhakr/Desktop/my_work
'test.txt.copy2'
['python_samples', 'test.txt', 'test', 'test.txt.copy', 'test.txt.copy2']
Move files
shutil.move(src, dst, copy_function=copy2)
The above method recursively moves the file from src to dst and returns the destination.
Reminders,
- 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 code 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
Code to move files:
# 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
shutil.move('test.txt',dest_dir)
# the file 'test.txt' is moved from src to dest
print(os.listdir())
os.chdir(dest_dir)
# list of files in dest
print(os.listdir())
Output
'/home/sradhakr/Desktop/my_work/python_samples/test.txt'
['python_samples', 'test', 'test.txt.copy', 'test.txt.copy2']
['.git', '.gitignore', 'README.md', 'src', 'test.txt']
Reference: https://docs.python.org/3/faq/windows.html