Renaming a File or Directory
Python rename directory: The Python os module provides a variety of functions for dealing with and interacting with the device’s underlying operating system.
The Python os.rename() function allows us to rename a file or directory directly from the command line or an IDE. The os.rename() function changes the name of the current directory or file to a specified/user-defined name.
Syntax:
import os os.rename(sourceaddress ,destinationaddress)
Parameters
sourceaddress: The file or directory’s current name.
destinationaddress: The name that will be used to replace the current name of the file or directory.
Return Value:
The os.rename() function produces no output. It just renames the file/directory provided.
- Python Interview Questions on File Manipulation
- Python : How to move files and Directories ?
- Python : How to copy files from one location to another using shutil.copy()
Example
To change the current working directory, use the os.chdir() function.
Approach:
- Import os module using the import Keyword.
- Pass the current directory or file name as an argument to the chdir() to change the current working directory.
- Rename the file/directory using the rename() function by passing oldname, newname as the arguments to it.
- Print some random text for success.
- The Exit of the Program.
Below is the implementation:
# Import os module using the import Keyword import os # Pass the current directory or file name as an argument to the chdir() to change # the current working directory os.chdir(r"C:\Users\vicky\Desktop") # Rename the file/directory using the rename() function by passing oldname, newname # as the arguments to it. os.rename("btechgeeks", "btechgeeksmodified") # Print some random text for success print("Congrats! your Directory/file has been successfully renamed.")
Output:
Congrats! your Directory/file has been successfully renamed.
Before Modification of directory:
After Modification of directory:
Renaming the File
Example: Using os.rename function
Approach:
- Import os module using the import Keyword.
- Pass the source directory/file path and destination path as the arguments to the rename() function to change the file name.
- Print some random text for success.
- The Exit of the Program.
Below is the implementation:
# Import os module using the import Keyword import os # Pass the source directory/file path and destination path as the argument to # the rename() function to change the file name os.rename("C:/Users/HP/OneDrive/Desktop/New.txt", "C:/Users/HP/OneDrive/Desktop/ss.txt") # Print some random text for success print("Congrats! your Directory/file has been successfully renamed.")
Output:
Congrats! your Directory/file has been successfully renamed.
Before Modifying file name:
After modifying file name: