A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/python/os_rename.htm below:

Python os.rename() Method

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 −

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


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4