gpt4 book ai didi

python - 当大小超过 1 MB 时按顺序创建新文件

转载 作者:行者123 更新时间:2023-12-01 06:46:59 27 4
gpt4 key购买 nike

我的下面的代码在位置创建异常日志文件-

C:/Users/Desktop/SampleTestFiles/ProjectFiles/ExceptionLogFiles/

最初,每当发生异常时,代码都会不断写入 ExceptionLog_1.txt 文件,并且当文件大小超过 1 MB 时,它会开始写入 ExceptionLog_2.txt 直到其大小达到 1 MB。到目前为止,它仅适用于这两个文件的创建和写入。当第二个文件的大小超过 1 MB 时,它应该将异常记录到第三个日志文件 ExceptionLog_3.txt 中。但是,它不起作用。代码继续写入第二个文件。

如何修改我的代码以确保当最新日志文件的大小超过 1 MB 时创建新文件?

def WriteExceptionToFile(self, traceback):

count = 1
fileDir = 'C:/Users/Desktop/SampleTestFiles/ProjectFiles/ExceptionLogFiles/'
# check if the path exists, create directory if not.
if not (os.path.exists):
os.mkdir(fileDir)

filename = "ExceptionLog_"+ str(count) +".txt"
filepath = os.path.join(fileDir, filename)

try:
if os.path.getsize(filepath) < 1048576: # if file size is less than 1 MB
filename = "ExceptionLog_" + str(count) + ".txt"
else:
filename = "ExceptionLog_" + str(count + 1) + ".txt"

except OSError:
Print("Path '%s' does not exists or is inaccessible" % filepath)
filename = "ExceptionLog_1.txt"

filepath = os.path.join(fileDir, filename)

with open(filepath, 'a+') as f:
traceback.print_exc(file=f)
f.close()

最佳答案

您还可以尝试使用logging模块中的轮换文件的方法。

直接来自文档的示例 ( https://docs.python.org/3/howto/logging-cookbook.html ):

import glob
import logging
import logging.handlers

LOG_FILENAME = 'logging_rotatingfile_example.out'

# Set up a specific logger with our desired output level
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)

# Add the log message handler to the logger, HERE YOU CAN SPECIFY THE FILE SIZE
handler = logging.handlers.RotatingFileHandler(
LOG_FILENAME, maxBytes=20, backupCount=5)

my_logger.addHandler(handler)

# Log some messages
for i in range(20):
my_logger.debug('i = %d' % i)

# See what files are created
logfiles = glob.glob('%s*' % LOG_FILENAME)

for filename in logfiles:
print(filename)

关于python - 当大小超过 1 MB 时按顺序创建新文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59181533/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com