[Python] file operation ④ (file operation | write data to file | use write function to write data to file | use flush function to refresh file data)





1. Write data to the file




1. Use the write function to write data to the file


Write data to the file by calling ;


The syntax is as follows −

write(string, file)

string is the data to be written, file is the file object to be written;


Usage example :

with open('file.txt', 'w') as f:  
    f.write('Hello, World!')

The open function is used to open the file, the 'w' parameter means to open the file in write mode;

The with statement is used to ensure that the file is automatically closed after use;

The write function writes a string to a file;


Note: Calling the write method does not write the data out to the file, but temporarily caches it in the buffer of the file;


2. Use the flush function to refresh the file data


After the write function is written, the content will not be written out to the file immediately, but temporarily cached in the buffer of the file, and the data in the buffer will be written out to the file at one time only after the flush function is called ;

The flush function is used to force the data in the buffer to be written to the file or stream immediately;

If data is not written to the file, it may be left in the buffer until the file is closed or the buffer is filled;

The flush function is usually used when data needs to be written to a file or stream immediately , for example when dealing with network connections or interacting with external devices;

Usage example :

with open('file.txt', 'w') as f:  
    f.write('Hello, world!')  
    f.flush()  # 将数据立即写入文件

The above code calls the flush function on the basis of the write function to refresh the buffer of the file;


The write and flush mechanisms are used to avoid frequent hard disk operations. Accessing hard disk operations is a time-consuming operation. It is recommended to accumulate enough data at one time and then write it to the hard disk at one time, which can improve the operating efficiency of the program;

The close function has a built-in flush function, and when the file is closed, the data in the file buffer will be written out to the file at one time;


3. Code example - use the write / flush function to write data to the file


In the following code, opening a file that does not exist will create a new file;

Use w write-only mode to write data, if the file already exists, the original content will be cleared and new content will be rewritten;


Code example:

"""
文件操作 代码示例
"""
import time

with open("file1.txt", "w", encoding="UTF-8") as file:
    print("使用 write / flush 函数向文件中写出数据: ")

    # 写出数据
    file.write("Hello World !")

    # 刷新数据
    file.flush()

    # 关闭文件
    file.close()

Results of the :

insert image description here

Guess you like

Origin blog.csdn.net/han1202012/article/details/131292735