Python os.rename() Method



The Python os.rename() method is used to change name of an existing file or directory. If the new file or directory name already present, OSError will be thrown.

To rename a file or directory, we need to pass both old path and new path as arguments to the rename().

Syntax

Following is the syntax for Python os.rename() method −

os.rename(src, dst, *, src_dir_fd, dst_dir_fd)

Parameters

The Python os.rename() accepts two parameters, which are as follows −

  • src − This is the existing name of the file or directory.

  • dst − This is the new name of the file or directory.

  • src_dir_fd − This parameter specifies a file descriptor referring to a directory.

  • dst_dir_fd − It is a file descriptor referring to a directory.

Return Value

The Python os.rename() method does not return any value.

Example

In the following example, we are renaming a directory named "tutorialsdir" to "tutorialsdirectory" using the rename() method.

import os, sys

# listing directories
print ("The dir is: %s"%os.listdir(os.getcwd()))

# renaming directory "tutorialsdir"
os.rename("tutorialsdir","tutorialsdirectory")

print ("Successfully renamed")

# listing directories after renaming "tutorialsdir"
print ("the dir is: %s" %os.listdir(os.getcwd()))

When we run above program, it produces following result −

The dir is:
 [  'a1.txt','resume.doc','a3.py','tutorialsdir','amrood.admin' ]
Successfully renamed
The dir is:
 [  'a1.txt','resume.doc','a3.py','tutorialsdirectory','amrood.admin' ]

Example

The rename() method throws "OSError" if the old file does not exist, or if the new file already exists. The below example illustrates how to handle such errors.

import os

try:
   # renaming 
   os.rename("newdir", 'tpwork')
except FileNotFoundError:
   print("The file or directory does not exist.")
except PermissionError:
   print("you don't have permissions to rename the file")
except OSError as error:
   print(f"Error: {error}")

When we run above program, it produces following result −

The file or directory does not exist.
python_files_io.htm
Advertisements