Home > Article > Backend Development > Introduction to file opening and closing operation commands in python
The following is an introduction to the file opening and closing operation commands in python. It has a good reference value and I hope it will be helpful to everyone. Let’s take a look together
1. File opening and closing
In python, use the open function to open an existing file. Or create a new file
open(filename, access mode).
f = open('test.txt', 'w')
File opening mode:
##Access mode | Instructions |
r | ##Open the file in read-only mode. The file pointer will be placed at the beginning of the file. This is the default mode.|
Open a file for writing only. If the file already exists, it is overwritten. If the file does not exist, create a new file. | |
Open a file for appending. If the file already exists, the file pointer will be placed at the end of the file. In other words, new content will be written after existing content. If the file does not exist, create a new file for writing. | |
Opens a file in binary format for reading only. The file pointer will be placed at the beginning of the file. This is the default mode. | |
Opens a file in binary format for writing only. If the file already exists, it is overwritten. If the file does not exist, create a new file. | |
#Opens a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. In other words, new content will be written after existing content. If the file does not exist, create a new file for writing. | |
Open a file for reading and writing. The file pointer will be placed at the beginning of the file. | |
Open a file for reading and writing. If the file already exists, it is overwritten. If the file does not exist, create a new file. | |
Open a file for reading and writing. If the file already exists, the file pointer will be placed at the end of the file. The file will be opened in append mode. If the file does not exist, a new file is created for reading and writing. | |
Opens a file in binary format for reading and writing. The file pointer will be placed at the beginning of the file. | |
Opens a file in binary format for reading and writing. If the file already exists, it is overwritten. If the file does not exist, create a new file. | |
Open a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. If the file does not exist, a new file is created for reading and writing. |
Note: When writing to open the file, write to close the file immediately # 新建一个文件,文件名为:test.txt
f = open('test.txt', 'w')
# 关闭这个文件
f.close()
Related Recommended:
The above is the detailed content of Introduction to file opening and closing operation commands in python. For more information, please follow other related articles on the PHP Chinese website!