The Wayback Machine - https://web.archive.org/web/20240625183246/https://www.geeksforgeeks.org/python-os-rename-method/
Open In App

Python | os.rename() method

Last Updated : 18 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system-dependent functionality.

To rename a file or directory in Python you can use os.rename() function of OS module. This method renames a source file or directory to a specified destination file or directory. It takes two parameters – source (current file name) and destination (new file name).

Syntax:

os.rename(source, destination, *, src_dir_fd = None, dst_dir_fd = None)

Parameters:

  • source: A path-like object representing the file system path. This is the source file path which is to be renamed.
  • destination: A path-like object representing the file system path. 
  • src_dir_fd (optional): A file descriptor referring to a directory. 
  • dst_dir_fd (optional): A file descriptor referring to a directory. 

Return Type: 

This method does not return any value.

Using os.rename() function and Error Handling:

Let’s see the program on how to use the os.rename function of the OS module and how to handle errors while using it.

Code 1: Use of os.rename() method.

Python3




# Python program to explain os.rename() method
 
# importing os module
import os
 
 
# Source file path
source = 'GeeksforGeeks/file.txt'
 
# destination file path
dest = 'GeekforGeeks/newfile.txt'
 
 
# Now rename the source path
# to destination path
# using os.rename() method
os.rename(source, dest)
print("Source path renamed to destination path successfully.")


Code 2: Handling possible errors

Python3




# Python program to explain os.rename() method
 
# importing os module
import os
 
 
# Source file path
source = './GeeksforGeeks/file.txt'
 
# destination file path
dest = './GeeksforGeeks/dir'
 
 
# try renaming the source path
# to destination path
# using os.rename() method
 
try :
    os.rename(source, dest)
    print("Source path renamed to destination path successfully.")
 
# If Source is a file
# but destination is a directory
except IsADirectoryError:
    print("Source is a file but destination is a directory.")
 
# If source is a directory
# but destination is a file
except NotADirectoryError:
    print("Source is a directory but destination is a file.")
 
# For permission related errors
except PermissionError:
    print("Operation not permitted.")
 
# For other errors
except OSError as error:
    print(error)


 

Reference Material: https://docs.python.org/3/library/os.html#os.rename

In this article, we have covered using os.rename() function to rename a file or directory in Python. This is a very easy and straightforward way of renaming a file or directory in Python. OS module provides a list of functions used to interact with the operating system.



Previous Article
Next Article

Similar Reads

Rename multiple files using Python
Prerequisite: OS module in PythonIn Python3, rename() method is used to rename a file or directory. This method is a part of the os module and comes in extremely handy. Syntax for os.rename() : os.rename(src, dst) : src is source address of file to be renamed and dst is destination with the new name. Now say given n images in a folder having random
2 min read
Python | Pandas Dataframe.rename()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas rename() method is used to rename any index, column or row. Renaming of column can also be done by dataframe.columns = [#list]. B
3 min read
Python | Pandas TimedeltaIndex.rename
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas TimedeltaIndex.rename() function set new names on index. It defaults to returning new index. Syntax : TimedeltaIndex.rename(name,
2 min read
Rename all file names in your directory using Python
Given multiple files in a directory having different names, the task is to rename all those files in sorted order. We can use OS module in order to do this operation. The OS module in Python provides functions for interacting with the operating system and provides a portable way of using operating system-dependent functionality. We can go to the cu
1 min read
Python | Pandas Series.rename()
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.rename() function is used to alter Series index labels or name for the given Se
2 min read
Python MongoDB- rename()
MongoDB is a cross-platform, document-oriented database that works on the concept of collections and documents. It stores data in the form of key-value pairs and is a NoSQL database program. The term NoSQL means non-relational. Refer to MongoDB and Python for an in-depth introduction to the topic. Now let's understand the use of rename() function i
2 min read
How to Rename a MySQL Table in Python?
MySQL Connector-Python module is an API in python used to communicate with a MySQL database server. It only requires the standard Python libraries and has no additional dependencies. There are various other modules in Python like PyMySQL and mysqlclient which can be used to access a database server. In this article, we will use MySQL Connector-Pyth
3 min read
Rename column name in MySQL using Python
In this article, we are going to see how we can rename or alter the name of a column table using Python. Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector-Python module is an API in python for communicating with a MySQL database. Ap
1 min read
Build a Bulk File Rename Tool With Python and PyQt
In this tutorial, we will learn how to create a file renaming tool using Python and PyQt5. PyQt5 is a set of Python bindings for the cross-platform application framework Qt, which is used to create graphical user interfaces (GUIs). We will use the OS module to interact with the file system, and the QFileDialog and QMessageBox classes from PyQt5 to
6 min read
Rename Nested Field in Spark Dataframe in Python
In this article, we will discuss different methods to rename the columns in the DataFrame like withColumnRenamed or select. In Apache Spark, you can rename a nested field (or column) in a DataFrame using the withColumnRenamed method. This method allows you to specify the new name of a column and returns a new DataFrame with the renamed column. Requ
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg