In today's article, we will learn about renaming and deleting files in python. As the name suggests, this article mainly talks about the two knowledge points of renaming files in python and deleting files in python.
Renaming and deleting files
Python's os module provides methods to help you perform file processing operations, such as renaming and deleting files.
To use this module, you must import it first, and then you can call various related functions.
rename() method: The
rename() method requires two parameters, the current file name and the new file name.
The syntax is as follows:
os.rename(current_file_name, new_file_name)
Example:
The following example will rename an existing file test1.txt.
# !/usr/bin/python # -*- coding: UTF-8 -*- import os # 重命名文件test1.txt到test2.txt。 os.rename("test1.txt", "test2.txt")
remove() method
You can use the remove() method to delete files. You need to provide the file name to be deleted as a parameter.
Syntax:
os.remove(file_name)
Example:
The following example will delete an existing file test2.txt.
# !/usr/bin/python # -*- coding: UTF-8 -*- import os # 删除一个已经存在的文件test2.txt os.remove("test2.txt")
The above is all about renaming and deleting files in python in this article. I hope what I said and the examples I gave can be helpful to you.
For more related knowledge, please visit the Python tutorial column on the php Chinese website.
The above is the detailed content of Python renames and deletes file definitions and functions (example analysis). For more information, please follow other related articles on the PHP Chinese website!