
๐Python File and Directory Renaming
Python File and Directory Renaming: Renaming files and directories in Python is simple with the os.rename() method. This method is part of Python’s built-in os module, designed to manage file operations effectively.
๐1. What is os.rename()?
The os.rename() method allows you to rename files or directories by specifying the source (current file name) and destination (new file name).
๐Python File and Directory Renaming Syntax:
python
os.rename(src, dst)
๐Python File and Directory Renaming Parameters:
- src: The current name of the file or directory. The file must already exist.
- dst: The new name for the file or directory.
๐2. Example: Renaming a File in Python
Let’s understand the process with a clear example.
๐Example Code:
python
import os
from os import path
def main():
# Check if the file exists
if path.exists(“Software Moji Moji.txt”):
# Rename the file
os.rename(‘Software Moji Moji.txt’, ‘career.Software Moji Moji.txt’)
print(“File renamed successfully!”)
if __name__ == “__main__”:
main()
๐Explanation:
โ
The code first checks if the file “Software Moji Moji.txt” exists.
โ
If the file is present, it renames it to “career.Software Moji Moji.txt” using os.rename().
โ
On successful execution, the new file name will appear in your directory.
๐Output:
arduino
File renamed successfully!
๐3. Important Notes on os.rename()
โ
The source file (src) must exist; otherwise, the code will raise a FileNotFoundError.
โ
The destination (dst) must not exist; otherwise, Python will overwrite the existing file.
โ
Ensure you have the necessary permissions to modify the file or directory.
๐4. Renaming a Directory Using os.rename()
The os.rename() method can also rename folders (directories) in Python.
๐Example Code for Directory Renaming:
python
import os
# Renaming a folder
os.rename(‘Old_Folder’, ‘New_Folder’)
print(“Directory renamed successfully!”)
๐5. Error Handling for os.rename()
To avoid unexpected errors, use a try-except block for better control.
๐Example Code with Error Handling:
python
import os
try:
os.rename(‘Old_File.txt’, ‘New_File.txt’)
print(“File renamed successfully!”)
except FileNotFoundError:
print(“Error: The specified file does not exist.”)
except PermissionError:
print(“Error: Insufficient permissions to rename the file.”)
except Exception as e:
print(f”An error occurred: {e}”)
๐6. Summary
โ
Use os.rename() to efficiently rename files and directories.
โ
Handle errors using try-except to prevent unexpected issues.
โ
Ensure the source file exists and the destination file does not conflict with existing files.