Today in this article we look at the renaming and deletion of files in Python, as the name implies, this article is mainly about Python renaming files and python delete files two points of knowledge.
Renaming and deleting files
Python's OS module provides a way to help you perform file processing operations, such as renaming and deleting files.
To use this module, you must first import it before you can invoke the various functions associated with it.
Rename () Method:
The rename () method requires two parameters, the current file name, and a new filename.
The syntax is as follows:
Os.rename (Current_file_name, New_file_name)
Example:
The following example renames a file that already exists test1.txt.
#!/usr/bin/python#-*-coding:utf-8-*-import os# rename file Test1.txt to Test2.txt. Os.rename ("Test1.txt", "Test2.txt")
Remove () method
You can delete the file using the Remove () method, and you need to provide the filename to delete as a parameter.
Grammar:
Os.remove (file_name)
Example:
The following example deletes a file that already exists test2.txt.
#!/usr/bin/python#-*-coding:utf-8-*-import os# Delete an existing file Test2.txtos.remove ("Test2.txt")