How To Rename File In Python?

Files are an important part of computer usage. Files are used to store different types of data like text, image, tabular data, voice, etc. Every file has a name in order to distinguish from other files and able to select for different operations. We can set the file names during file creation but also change later too. Python programming language provides the os.rename() and shutils.move() function in order to change file names. We can also use these functions to add a timestamp or change specific file extensions/types names as well. These functions can be used for both Windows and Linux.

Rename File with os.rename() Function

The rename() function which is provided via the os module is the standard function to rename files. The rename() function is provided inside the os module because of the system related functionality. Let’s take a look for the os.rename() function syntax below.

os.rename(src,dst,src_dir,dst_dir)
  • src is the source file name we want to change or rename this can be only the name of the file if it is a current working directory or if the src_dir_fd is specified. Also, we can provide the full path with the name of the source file without using the src_dir. src parameter is a must and should be provided.
  • dst is the destination file name we want to change or rename. This can be only the name of the file if it is in the current working directory or if the dst_dir_fd is specified. Also, we can provide the full path with the name of the source file without using the dst_dir_fd. dst parameter is a must and should be provided.
  • src_dir_fd is optional and can be used to specify the path of the source file.
  • dst_dir_fd is optional and can be used to specify the path of the source file.

Now we can make a simple example in order to rename the file named poftut.txt into the wisetut.txt. Keep in mind that we should import the os module.

import os

#Rename poftut.txt into wisetut.txt
os.rename('poftut.txt','wisetut.txt')

If we want to work in different then the current working directory we should provide the complete or full path of the files. You can see that we provide different directories for the source and destination files named /home/ismail and /home/ahmet.

import os

#Rename poftut.txt into wisetut.txt
os.rename('/home/ismail/poftut.txt','/home/ahmet/wisetut.txt')

An alternative and more elegant way to provide a full path by joining the path and file is using the os.path.join() function like below.

import os

source_file = os.path.join('/home/ismail/','poftut.txt')
destination_file = os.path.join('/home/ahmetl/','wisetut.txt')

#Rename poftut.txt into wisetut.txt
os.rename( source_file , destination_file)

We can extend our example and check the source file existence by using the path.exists() method which is provided via the os.path module.

import os
import os.path

#Check if poftut.txt exist
if path.exists("poftut.txt"):
   #Rename poftut.txt into wisetut.txt
   os.rename('poftut.txt','wisetut.txt')
else:
   print("The poftut.txt doesn't exist")

We can make our file rename code more complete by checking the source file and destination file name with the path.exists() function. You can also provide the full path of the file in order to check its existence.

import os
import os.path

#Check if poftut.txt exist
if path.exists("poftut.txt") and path.exists("wisetut.txt"):
   #Rename poftut.txt into wisetut.txt
   os.rename('poftut.txt','wisetut.txt')
else:
   print("The poftut.txt doesn't exist or wisetut.txt allready exist")

Rename Specific File Extension/Type

Another popular use case is renaming files according to their extensions of file type. There are different ways to accomplish this. But below we will provide practical ones. We will use the glob function of the glob library which can list files according to their extensions and use with the for loop.

import glob
import os

count=0

for src in glob.glob('*.txt'):
   dst="WiseTut"+str(count)+".txt"
   os.rename(src,dst)
   count++

Rename Multiple Files

Multiple files can be renamed by using loops and enumerating the files. In the following example, we will use the os.listdir() function to get a list of files and enumerate with for loop. In each step, we will use the os.rename() function for the current file.

import os 

for count, filename in enumerate(os.listdir("/home/ismail/")):
   dst="WiseTut"+str(count)+".txt"
   src = filename
   os.rename(src,dst)

Rename File and Replace If Already Exist

Python rename() function will rais an error if the destination file already exists. This can be solved with replacing where the os.replace() function can be used. The replace() function has the same syntax with the rename() function. Below we will replace the poftut.txt with the wisetut.txt even the wisetut.txt already exist.

import os

os.replace('poftut.txt','wisetut.txt')

Rename File By Moving with shutil.move() Function

The Python shutil module provides the move() method where give source file will be moved to the specified destination file name. The move is the same operation with the rename. We can use the shutil.move() method in order to rename files like below. The following code will work in Python 3.0 or later.

import shutil

shutil.move("poftut.txt","wisetut.txt")

Rename File Errors

Renaming files with the os.rename() function is not error-free. you may get different errors for different cases. Below we will list some of the common error types and solutions while renaming files with the Python programming language. The following code will handle the exceptions to make the rename function flawless.

import os

try:
   os.rename("poftut.txt","wisetut.txt")

except IsADirectoryError:
   print("The source file name is a directory not a file")

except NotADirectoryError:
   print("Source file name is a directory not a file")

except PermissionError:
   print("There is not permission for the source or destination file")

except OSError as er:
   print(er)
  • ADirectoryError is thrown if the source a file but destination is a directory which is exist. Check if there is no directory named with the specified destination file name.
  • NotADirectoryError is thrown if the source is not a file but a directory. Check given source file names are correct.
  • PermissionError is mainly related the current user do not have permission to read or write for the source or destination file. Give permission to the current user with the chmod in Linux or File/Folder attributes in Windows.
  • OSError is a more generic error which can be thrown for different reasons. Check the file system, disk or if the source file is already opened by another process.

Leave a Comment