×

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's Qstandarditemmodel

Python More interactive and user-friendly than any other programming language is Python. Many libraries are used by the python programming language to speed up procedures. Python can be used to develop...

3 minutes read.

Spyder (32-bit) - Free download

Spyder is a free and open-source scientific environment created by and for Python engineers, scientists, and data analysts. It is a robust scientific environment created in Python by and for...

3 minutes read.

Pointers in Python

In this tutorial, we will study what pointers are and if they have any utility in python. Now, let us understand what pointers are Pointers Pointers are special variables used to store the...

3 minutes read.

Python String upper() method

Python String upper() method The string.upper() method in Python returns a copy of the string converted to uppercase. Syntax string.upper() Parameter NA Return This method returns a copy of the string converted to uppercase. Example 1 # Python...

1 minute read.

Append key Value to Dictionary in Python

The Python dictionary is one of the built-in data types. Elements of dictionaries are key-value pairs. In Python, there are numerous ways to add dictionaries. Let's examine some of the...

9 minutes read.

How to convert integer to float in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

5 minutes read.

Python String isalpha() method

Python String isalpha() method The string.isalpha () method in Python returns a boolean value true if all characters in the  string are alphabetic else for any other value it returns false. Syntax isalpha()  Parameter NA Return This...

1 minute 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 Lists vs Tuples

The difference between lists and tuples is one of the most frequently asked questions in an interview related to python language. Lists and Tuples are two of Python’s built-in data...

4 minutes read.

Explain sklearn clustering in Python

Make a connection and patterns across datasets by using clustering, one of the unsupervised machine learning approaches. Grouping is crucial because it ensures unlabelled data's natural clustering. The sample from...

7 minutes read.

Adding a key-value pair to dictionary in Python

Python dictionaries are collections of unsorted key-value pairs. This article will examine a method for adding new key-value teams to an existing dictionary. Dictionary in Python With the aid of curly brackets...

3 minutes read.

Python Unit Test Cheat String

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Python Program to Find the gcd of Two Numbers

Introduction Greatest Common Divisor is the full form of gcd. The greatest common divisor, or GCD, of two numbers, is a value that can exactly divide the two digits and is...

5 minutes read.

Python Scikit-image | Image Processing Using Scikit-Image

What is Image Processing? The world is defined with images and, every image has its different specialties. An image can contain much-needed information that can be helpful in various ways. The process...

4 minutes read.

Iterators in Python

Introduction In Python, an iterator is defined as an object that enables traversing through all the values of a collection. It contains the countable number of values. The iterator is utilized to...

4 minutes read.

How to Download Python

How to Download Python Python is the most renowned programming language and developers across the globe are working on projects that are made using Python and its libraries. Here we will...

4 minutes read.

Checking whether a String Contains a Set of Characters in python

In this tutorial, we will learn how to examine or check whether a string contains any set of characters or a substring and if it contains, we will learn how...

6 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.

Android apps for coding in python

Nowadays, it is the generation of smartphones. The world can be seen and acknowledged with a single click on your mobile phone. Everyone uses mobile phones to do any work,...

9 minutes read.

Python EOL (End Of Line)

Introduction An EOL (End Of Line) is defined as a syntax error that indicates that the Python interpreter reached at the end of the line when it tried to scan a...

3 minutes read.