Article directory
1. Write data to the file
1. Write data to an existing file in read-only mode
Using the write function to write data to an existing file will clear the data in the file. The code is shown as follows:
The content of the file1.txt file is Hello World !
, now open the file in write-only mode, and write the file to file1.txt;
Code example:
"""
文件操作 代码示例
"""
import time
with open("file1.txt", "w", encoding="UTF-8") as file:
print("使用 write / flush 函数向文件中写出数据(以只读方式打开文件): ")
# 写出数据
file.write("Tom and Jerry")
# 刷新数据
file.flush()
# 关闭文件
file.close()
Execution result: After executing the above code, file1.txt becomes Tom and Jerry
, and the content in the previous file is cleared;
2. Write data to an existing file in append mode
The append mode is a
the mode , use the open function to open the file in append mode:
- If the file does not exist, it will be created;
- If the file exists, the original content of the file remains unchanged, and data is appended at the end of the file;
Open file code in append mode:
open("file1.txt", "a", encoding="UTF-8")
The function of the above code is: open the file1.txt file, a
open it , and the encoding of the file is UTF-8;
Code example:
"""
文件操作 代码示例
"""
import time
with open("file1.txt", "a", encoding="UTF-8") as file:
print("使用 write / flush 函数向文件中写出数据(以追加模式打开文件): ")
# 写出数据
file.write("Tom and Jerry")
# 刷新数据
file.flush()
# 关闭文件
file.close()
Execution result: after execution, the Hello World!
file is appended with Tom and Jerry
data on the basis of the text, and finally the data in the file is obtained as follows Hello World!Tom and Jerry
;
3. Open a non-existent file in append mode
In the open function, use the append mode a
to open a non-existing file, and then create the file and write data to it;
Code example:
"""
文件操作 代码示例
"""
import time
with open("file2.txt", "a", encoding="UTF-8") as file:
print("使用 write / flush 函数向文件中写出数据(以追加模式打开文件): ")
# 写出数据
file.write("Tom and Jerry")
# 刷新数据
file.flush()
# 关闭文件
file.close()
Execution result: Open the file2.txt file. If there is no such file at this time, a new file2.txt file will be created. After writing the content, the content of the file is Tom and Jerry
, which is the newly written data;