代码执行期间无法切换Python日志文件名称

时间:2019-05-19 15:04:28

标签: python python-3.x

我试图在下面的代码的每个for循环中更改要写入的日志文件。但是,由于日志文件名尚未更新,因此在第二个循环结束时出现了错误。

我需要更改我的代码吗?

from datetime import datetime
import logging

master_list = ['1']


for fr_var in master_list:



    logfile1 = '{}{}_{}.{}'.format('G:\\Python27\\Test\\', 'Export_Logfile_', datetime.now().strftime("%Y%m%d%H%M%S"), 'log')


    logging.basicConfig(level=logging.INFO,
    format='%(asctime)s - %(name)8s - %(levelname)5s - %(message)s',
    filename=logfile1,
    filemode='w')    
    logging.captureWarnings(True)

    log = logging.getLogger(__name__)




    log = logging.getLogger()  # root logger

    for hdlr in log.handlers[:]:  # remove all old handlers

        log.removeHandler(hdlr)

    logging.shutdown()

    with open(logfile1, 'r+') as f:
        content = f.read()
        f.seek(0, 0)
        f.write('=============================================================')
        print('test')
        f.write('=============================================================' + content)





    for fr_var in master_list:


        logfile2 = '{}{}_{}.{}'.format('G:\\Python27\\Test\\', 'Import_Logfile_', datetime.now().strftime("%Y%m%d%H%M%S"), 'log')
        log.addHandler(logfile2) 


        logging.basicConfig(level=logging.INFO,
        format='%(asctime)s - %(name)8s - %(levelname)5s - %(message)s',
        filename=logfile2,
        filemode='w')    
        logging.captureWarnings(True)

        log = logging.getLogger(__name__)



        log = logging.getLogger()  # root logger

        for hdlr in log.handlers[:]:  # remove all old handlers

            log.removeHandler(hdlr)

        logging.shutdown()

        with open(logfile2, 'r+') as f:
            content = f.read()
            f.seek(0, 0)
            f.write('=============================================================')
            print('test')
            f.write('=============================================================' + content)

错误:

Traceback (most recent call last):
  File "G:/Python36/Test/Test.py", line 69, in <module>
    with open(logfile2, 'r+') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'G:\\Python27\\Test\\Import_Logfile__20190519160145.log'

0 个答案:

没有答案