In Python, you can easily rename a file using the os
module. The os
module provides a way to interact with the operating system, including renaming files. To rename a file, you can use the os.rename()
function.
Syntax
os.rename(src, dst)
Where:
src
is the current name of the file you want to renamedst
is the new name you want to give the file
Example
import os #Current name of the file src = "old_file.txt" #New name of the file dst = "new_file.txt" #Rename the file os.rename(src, dst)
In this example, the file old_file.txt
is renamed to new_file.txt
using the os.rename()
function. The src
variable holds the current name of the file and the dst
variable holds the new name of the file. The os.rename()
function takes these two arguments and renames the file accordingly.
Note
It’s important to note that the os.rename()
function will raise an error if the destination file already exists. To avoid this, you can check if the destination file already exists and delete it before renaming the source file. For example:
import os #Current name of the file src = "old_file.txt" #New name of the file dst = "new_file.txt" #Check if the destination file already exists if os.path.exists(dst): os.remove(dst) #Rename the file os.rename(src, dst)
In this example, the code checks if the destination file new_file.txt
already exists using the os.path.exists()
function. If it exists, the code deletes it using the os.remove()
function before renaming the source file.
Conclusion
Renaming files in Python is a simple process that can be accomplished using the os
module and the os.rename()
function. Whether you’re renaming a single file or multiple files, the process remains the same. Just make sure to handle potential errors and exceptions that may occur, such as a destination file already existing, and you’ll be able to rename your files with ease.