python写文件时,使用代码强制刷新文件

一、实验环境

1.Windows10x64

2.anaconda4.6.9 + python3.7.1(anaconda集成,不需单独安装)

3.pyinstaller3.5

二、任务需求

三、问题描述

1.文件1中内容,添加至总文件后,被后续的文件2覆盖!

2.文件1添加至总文件后,添加一行打印语句(打印语句执行需要时间),未被后续文件2覆盖!

四、问题分析

怀疑python写入文件,Windows操作系统未及时刷新,未执行真正的写动作,存在短暂延时,需要使用文件刷新函数。

五、文件刷新

1.为什么要刷新文件呢

答:首先我们就要知道电脑是怎么储存信息的,写的代码保存在缓存中当缓存满了之后就会将内容储存到硬盘中。

2.为什么要刷新文件

答:系统会自动储存信息,但是储存信息不及时,将导致快速操作同一文件失败或者意外断电后数据丢失。

六、文件刷新代码例子

def save_file(context=None,file_path=None):
    """
    :param context: write content
    :param file_path: write file path
    :return:
    """
    try:
        df = open(file_path,'wb')
        if context:
            bin2str = binascii.a2b_hex(context)
        else:
            bin2str = binascii.a2b_hex(self._intercept_contents_filter)
        debug_print(bin2str)
        df.write(bin2str)
        df.flush()                                      #强制刷新
    finally:
        if df:
            df.close()

  

原文地址:https://www.cnblogs.com/hester/p/12058363.html