Copy and rename files in Python

Python copy and rename files: Here, we are going to learn how to copy and rename the files in Python using shutil module functions?
Submitted by Sapna Deraje Radhakrishna, on September 30, 2019

Using shutil (shell utilities) module, file operation such as copy, rename, move, etc is very handy. To copy and rename, there are two approaches:

  1. Move the file with new name
  2. Copy and rename file using 'OS' module

1) Move and Rename file

move function

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

The above method recursively moves the file from src to dst and returns the destination.


  • 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 for move and rename file

List command:

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

More & rename files:

# Importing the modules
import os
import shutil

# gets the current working dir
src_dir = os.getcwd() 
# defining the dest directory
dest_file = src_dir + "/python_samples/test_renamed_file.txt"

# moving

# listing the files 


# list of files in dest


'/home/sradhakr/Desktop/my_work/python_samples/ test_renamed_file.txt'
['python_samples', 'test', 'test.txt.copy', 'test.txt.copy2']
['.git', '.gitignore', '', 'src', ' test_renamed_file.txt']

Copy and rename using os and shutil module

In this approach we use the shutil.copy() function to copy the file and os.rename() to rename the file.

# Importing the modules
import os
import shutil

src_dir = os.getcwd() #get the current working dir

# create a dir where we want to copy and rename
dest_dir = os.mkdir('subfolder')

dest_dir = src_dir+"/subfolder"
src_file = os.path.join(src_dir, 'test.txt.copy2')
shutil.copy(src_file,dest_dir) #copy the file to destination dir

dst_file = os.path.join(dest_dir,'test.txt.copy2')
new_dst_file_name = os.path.join(dest_dir, 'test.txt.copy3')

os.rename(dst_file, new_dst_file_name)#rename



['python_samples', 'subfolder', 'test', 'test.txt.copy2', 'test.txt.copy_1']


shutil (shell utilities module ) is a more pythonic way to perform the file or directory copy , move or rename operations.


Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.