×

os.rename() method in Python

In Python, the os module provides the capacity to interact with the operating system. The operating system comes under the Python module. In this module, Python provides a specific feature that depends on the operating system. This module's main feature is interacting with the file and path directory. In this article, we will learn about Python's os.rename features.

Rename file in Python

In order to rename a file, the first thing we need is the path of the file. The path is the location of the file on the disk in a computer system. To be more particular, an Absolute path contains the complete directory list required to locate the file, and a Relative path contains the current directory and then the file name.

The os.rename() method

In Python, the os module provides a method to rename the file and directory name through the python program. 

Syntax for os.rename() method

We can implement the os.rename() method by the use of the following syntax. The syntax is as follows:

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

Parameter for os.rename() method

There is some parameter that is used in the os.rename() method. These parameters are as follows:  

  1. Source: It is a path that shows the path of the file system. We have to rename that path through the python program.
  2. Destination: It is also a path-like object which represents the path of the file system.
  3. src_dir_fd (optional): It is a type of file descriptor that refers to the directory.
  4. dst_dir_fd (optional): It is also a type of file descriptor that refers to the directory.
  5. Return Type: This method does not have any return value. 

Example 1:

# Python program to explain os.rename() method
 
# importing os module
import os
 
 
# Source file path
source = 'javatpoint/demo.txt'
 
# destination file path
dest = 'javatpoint/newdemo.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.")

Output:

 Source path renamed to destination path successfully.

Example 2:

# Python program to explain os.rename() method
 
# importing os module
import os
 
 
# Source file path
source = './javatpoint/demo.txt'
 
# destination file path
dest = './javatpoint/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)

Output:

Source path renamed to destination path successfully.

Example 3:

import os, sys
 
# listing directories
print "The dir is: %s"%os.listdir(os.getcwd())
 
# renaming directory ''sonudir"
os.rename("sonudir","sonudirectory")
 
print "Successfully renamed."
 
# listing directories after renaming "sonudir."
print "the dir is: %s" %os.listdir(os.getcwd())\

Output:

The os.rename() method in Python

Renaming only the Extension of the file in Python

Sometimes, we just want to rename the extinction name through the help of the os.rename() method. This can be done by performing the split text operation in the program. Then only we can rename the extension name. This os method returns both the root and extension name separately. Once we get the root name of the file path, then we can add the new extension name to the file path with the help of the os.rename() method.

Example 4:

import os


# Selecting the list
print('Before rename:')
file = file.txt
print(file)


# Renaming the file
for file_name in file:


# construct full file path
old_file_name = os.path.join(folder, file_name)


# Change the Extension from txt to pdf
new_file_name = old_file_name.replace('.txt', '.pdf')
os.rename(old_file_name, new_file_name)
print('After rename:')
print(file)

Output:

The os.rename() method in Python

Renaming a file in Python is as easy as naming a file. The Os module in Python renames a file name and other functions.


Related Topics

Python Dictionary clear() method

Python Dictionary clear() method The dictionary.clear() method in Python removes all the elements from a dictionary. Syntax dictionary.clear() Parameter NA Return None Example 1 # Python program explaining # the dictionary.clear() method # initialising the dictionary fruits =...

1 minute read.

What is Python online compiler?

The compiler is a program that is used to scan an entire high-level program (source code) and it translates the scanned program into machine code. Compilers convert .py source code into...

5 minutes read.

How to run a Program in Python

How to run a Program in Python Writing a program in Python is an easy task, beginners who are ready to kickstart their career in the world of programming can create...

3 minutes read.

Python Classification

Identification and grouping of items or concepts into specified categories this process is known the classification. Data can be separated and sorted in data management according to predetermined criteria for...

6 minutes read.

Joint Plot in Python

Introduction to Joint plots: The joint plot is the finest approach to evaluate both the specific distribution of each variable and also the connection between the two variables. Three different plots make...

4 minutes read.

Magento 2 Site optimization

Magento 2 Site optimization Magento 2 is a CMS, commonly referred to as Intensive efficiency. Improving the speed and reliability of your Magento 2 app helps clients to achieve a better user experience while...

2 minutes read.

Change Data Type in Python

Python is a dynamic language where it is not always required to consider every variable type. Python supports a wide range of data types, but There are mainly six data...

3 minutes read.

Converting Set to List in Python

Converting ‘set’ datatype to ‘list’ datatype is called typecasting. Typecasting in programming is a method to convert one datatype into another datatype. It may happen implicitly by the defined language, called...

3 minutes read.

Expressions in Python

What is Expression in Python? The expression contains more than one operator as well as the operands with it. Expression helps us to produce some other values. In the Python programming...

12 minutes read.

Python Command line Arguments

Python Command line Arguments The command-line argument is used to the change functionality of the program. It's an extra command the programmer can use while launching a program. These commands have many uses...

7 minutes read.

Cursor in Python

The cursor is an item that aids in query execution and records retrieval from databases. The cursor is crucial to the execution of the query. In-depth information on the execution...

7 minutes read.

IPython Display

A command shell, often known as IPython is a software application that makes an operating system's features accessible to users or other applications. Based on the purpose and specific functioning...

6 minutes read.

Paramiko Python Example

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

6 minutes read.

How to plot multiple linear regression in Python

This article lets us look into linear regression in Python and how we can plot multiple linear regressions in it. Linear regression One of the simplest and most widely used Machine Learning...

4 minutes read.

Periodogram in Python

Python:  Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Genetic Algorithm in python

Python : Python is an object oriented programming language which is highly interpreted and is highly interactive. Python was created by Guido van Rossum in the year 1985 – 1990 .The source...

4 minutes read.

List Comprehension in Python

Sometimes we need new lists that are completely based on previously existing lists, so to perform this operation successfully, some of the programming languages come with a syntactic construct known...

5 minutes read.

Python Basics

In this tutorial, we will learn about the basics of Python, a very famous programming language. This tutorial will help you understand the language better if you start with python....

8 minutes read.

Python for Data Analysis

Data analysis uses various techniques to read, illustrate, manipulate and evaluate a particular data. You can have access to the data and keep the data updated regularly. You can append...

4 minutes read.

Bar Plot in Python

A bar chart or bar graph displays categorical data using rectangular bars with heights or lengths proportionate to the values for the data distributed in the dataset. In a bar...

16 minutes read.