| by Arround The Web | No comments

Python Rename File

Renaming files” is a common task in various programming applications, and Python provides an efficient and versatile approach for accomplishing this. Through its robust file-handling capabilities, Python enables developers to explore various techniques for “renaming files”, both locally and remotely.

This article aims to delve into the intricacies of “file renaming” in Python, discussing essential methods to equip the reader with a comprehensive understanding of this subject.

File Systems and Paths

Before diving into “file renaming”, it is crucial to develop an understanding of file systems and paths. Python’s “os” module provides a set of functions that allow us to interact with the underlying operating system, enabling file path manipulations. By utilizing methods like “os.path()” and “os.chdir()”, developers can navigate directories and access files using absolute or relative paths.

How to Rename Files in Python?

By employing functionalities like “os.rename()” or “shutil.move()”, developers can modify the name or extension of a file in a given directory. Additionally, by utilizing looping structures and conditional statements, it is possible to automate the renaming process for a batch of files. Some of the approaches include the following:

Approach 1: Renaming the File Using the “os.rename()” Function

To rename a single file using Python, employ the “os.rename()” function by passing the original and desired file names as arguments. Integration with user input, exception handling, and file existence checks will be demonstrated to ensure robustness and avoid errors.

Syntax

os.rename(src, dst)

 

In this syntax, the source address of the file to be renamed is given as “src”, and the destination is given as “dst”.

Suppose, we have this file named “linuxHint.txt” that needs to be renamed:

Now, to rename this file, consider the following code:

import os
 
old_name = "D:\linuxHint.txt"
new_name = "D:\linux.txt"

os.rename(old_name, new_name)
 
print("File renamed")

 

In the above code lines, import the “os” module first and then specify the existing and new file names. It is such that the file is renamed from “linuxHint.txt” to “linux.txt” using the “os.rename()” function.

Output

Renamed File

Approach 2: Renaming the File Using the “shutil” Module

The “shutil” module in Python presents advanced file-handling functionalities, including renaming files across different directories. With methods such as “shutil.move()”, it is possible to move files while simultaneously renaming them, facilitating directory restructuring or organization tasks:

Syntax

shutil.move(source, destination, copy_function = copy2)

 

Parameters

source: A string containing the source file’s location.

destination: A string containing the directory’s path information.

copy_function: Optional. Copy2 is the default value for this parameter. For this argument, we can also utilize alternative copy functions like copy and copy tree.

Now look at the code example:

import shutil
 
old_name = "D:\linux.txt"
new_name = "D:\linuxHint.txt"
 
shutil.move(old_name, new_name)
 
print("File renamed.")

 

The above code block first imports the “shutil” module and then specifies the old and new file names. The file is then renamed from “linux.txt” to “linuxHint.txt” via the “shutil.move()” method.

Output

Renamed File

Approach 3: Renaming Multiple Files Using the “os.listdir()” Function

In real-world scenarios, developers may need to handle multiple files simultaneously. Python allows for bulk renaming through various techniques, such as the “os.listdir()” function to get a list of the files in a directory, and you can then cycle through the files to rename them.

Syntax

os.listdir(path)

 

path: Optional. Path of the directory.

Following are the files that need to be renamed:

To rename multiple files, overview the below-given code:

import os
 
dir = "D:\linuxhint"
pre = "new_"
 
for file_name in os.listdir(dir):
    if file_name.endswith(".txt"):
        new_name = pre + file_name
        os.rename(os.path.join(dir, file_name), os.path.join(dir, new_name))
 
print("Files renamed.")

 

This code snippet will rename any text files—those with the “.txt” extensions—found in the specified directory, “D:linuxhint“. The destination directory and a prefix string “new_” are initially set, which will be appended to the start of each renamed file. The “os.listdir()” function is then used by the script to loop through each file in the directory.

It creates a new name for every file with a “.txt” extension by adding the prefix to the original file name. The file in the directory is then renamed using the “os.rename()” function, replacing the old name with the new name. It prints the message “Files renamed.” once all the target files have been renamed.

Output

Renamed Multiple Files

Conclusion

Mastering file renaming in Python empowers developers to efficiently manage file operations both locally and remotely. By using the “os.rename()” function, or “shutil.move()” method, users can rename the files using Python. Python also allows for multiple renaming of files via the “os.listdir()” function to get a list of the files in a directory, and you can then cycle through the files to rename them.

Share Button

Source: linuxhint.com

Leave a Reply