【问题标题】:Python Logging - Make a log file which list the files that raise an error in For loopPython Logging - 创建一个日志文件,列出在 For 循环中引发错误的文件
【发布时间】:2020-12-20 08:37:41
【问题描述】:

我正在循环中尝试一些操作

from obspy import read
for file in glob.glob('*.*'):
    st=read(file)

但是目录中的某些特定文件无法读取,并且出现错误。 我想制作一个日志文件,其中列出了文件的文件名(带路径),这给了我使用 logging 模块的错误。

我正在尝试打开一个文本文件并在其上写入文件名(不知何故,有时即使出现错误,我也会得到一个空文件),

f=open('log_response.txt','w')
 
for file in glob.glob('*.*'):
    try:
    # block raising an exception
       st=read(file)
    except:
    #If there is any error write the filename to the file or pass
       f.write('{}\n'.format(os.path.abspath(file)))
       pass
    else:
        print(st)

f.close()

但我想使用logging 模块 我该怎么做?

【问题讨论】:

    标签: python for-loop logging error-handling


    【解决方案1】:

    试试这个:

    import logging
    
    logging.basicConfig(handlers=[logging.FileHandler(filename="log_response.txt",
                                                     encoding='utf-8', mode='a+')],
                        format="%(asctime)s %(name)s:%(levelname)s:%(message)s",
                        datefmt="%F %A %T",
                        level=logging.INFO)
    
    
    
    for file in glob.glob('*.*'):
        try:
            st = read(file)
        except:
            logging.error('{}'.format(os.path.abspath(file)))
            pass
    

    【讨论】:

      猜你喜欢
      • 2013-07-21
      • 1970-01-01
      • 2017-08-20
      • 1970-01-01
      • 2013-08-19
      • 1970-01-01
      • 1970-01-01
      • 2023-01-24
      • 2021-11-02
      相关资源
      最近更新 更多