Renaming and deleting files in Python
Renaming and Deleting Files in Python
Python The os module provides methods that help you perform file manipulation operations, such as renaming and deleting files.
To use this module, you need to import it first, then call any of the associated functions.
rename() Method
The rename() method accepts two parameters: the current file name and the new file name.
Syntax
os.rename(current_file_name, new_file_name)
Example
The following is an example of renaming the existing file “test1.txt” to “test2.txt”:
#!/usr/bin/python3
import os
# Rename a file from test1.txt to test2.txt
os.rename( "test1.txt", "test2.txt" )
remove() Method
You can use the remove() method to remove a file by providing the name of the file to be removed as an argument.
Syntax
os.remove(file_name)
Example
The following example deletes the existing file “test2.txt”:
#!/usr/bin/python3
import os
# Delete file test2.txt
os.remove("text2.txt")