Python Programming – Renaming and Deleting Files
Python language provides special methods for renaming and deleting a file. These methods are available through the Python os module. For using these methods, the programmer needs to import the os module. Both of these methods are very easy to use and described below:
rename( ) method
The rename( ) method takes two arguments. The syntax of rename( ) method is given as follows:
The programing example for using the rename( ) is given in Code 9.13. We see that the data.txt file already exists. By using the rename( ) method, it is renamed to info.txt. The programmer can see in the current directory that the file has been renamed.
Code: 9.13. Illustration of renameO method.
|#Illustration of renaming a file
remove( ) method
The remove( ) method is used to delete the file. It has only one argument, which is the file name to be deleted. The syntax of remove( ) is given as follows:
The programming example for using the remove( ) method is given in Code 9.14. This program removes the file from the current directory. After the execution of this program, the programmer can see that the file will not be present in the current directory and can be obtained from the recycle bin.
Code: 9.14. Illustration of remove method.
|# Illustration of deleting a file