Examples for os.rename

Renaming a File

It will rename the file ‘old_file.txt’ to ‘new_file.txt’ and display a message indicating that the renaming process was successful.

Python3




import os
 
# Current file name
old_name = 'old_file.txt'
 
# New file name
new_name = 'new_file.txt'
 
# Rename the file
os.rename(old_name, new_name)
 
print(f"File '{old_name}' has been renamed to '{new_name}'.")


Output:

File is renamed as GFG

Rename a Directory

It will rename the directory ‘old_directory’ to ‘new_directory’ and display a message indicating that the renaming process was successful.

Python3




import os
 
# Current directory name
old_dir = 'old_directory'
 
# New directory name
new_dir = 'new_directory'
 
# Rename the directory
os.rename(old_dir, new_dir)
 
print(f"Directory '{old_dir}' has been renamed to '{new_dir}'.")


Output:

Rename a Directory

Difference Between os.rename and shutil.move in Python

When it comes to renaming or moving files and directories, two commonly used methods are os. rename and shutil. move. While both can serve the purpose of renaming and moving, they have distinct differences in terms of functionality and use cases. In this article, we will explore these differences and when to use each of them.

Similar Reads

Difference Between os. rename and shutil. move in Python

Both os. rename and shutil. move are valuable tool in Python for renaming and moving files and directories. The choice between them depends on the complexity of your task and the specific requirements of your file manipulation operation....

Examples for os.rename

Renaming a File...

Examples for shutil.move

...