您可以在写入日志前检查文件大小,并根据需要切换到下一个文件进行日志写入。可以使用os模块来获取文件大小。以下是一个示例代码:

import os

def setGuardLog(str_log):
    file_path = '/home/debug/guardLog/GuardOperation.txt'
    max_file_size = 1024 * 1024  # 1MB

    # 检查文件大小
    if os.path.exists(file_path) and os.path.getsize(file_path) > max_file_size:
        # 获取当前文件名的数字部分
        current_file_number = int(file_path.split('.')[0][-1])
        next_file_number = current_file_number + 1

        # 构建下一个文件的路径
        next_file_path = file_path.replace(str(current_file_number), str(next_file_number))

        # 切换到下一个文件进行日志写入
        with open(next_file_path, 'a+') as f:
            f.write(str_log + '*&*&*' + get_time() + '\n')
        f.close()
    else:
        # 文件不存在或未达到大小限制,继续写入当前文件
        with open(file_path, 'a+') as f:
            f.write(str_log + '*&*&*' + get_time() + '\n')
        f.close()

在上述代码中,我们首先检查GuardOperation.txt文件的大小是否超过1MB。如果超过了,我们会根据当前文件名的数字部分构建下一个文件的路径,并在下一个文件中写入日志。如果文件不存在或未达到大小限制,则会继续写入当前文件。

请注意,上述代码仅提供了一个基本的实现思路,您可能需要根据实际情况进行适当的修改和调整

def setGuardLogstr_log with openfhomedebugguardLogGuardOperationtxt a+ as f fwritestr_log + && + get_time + n fclose如何做到 GuardOperation 文件达到1mb 切换下一个文件写入log

原文地址: http://www.cveoy.top/t/topic/h9ZM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录