我想创建一个日志文件,每次发生错误时都会在文本文件 log.txt 中添加一个新行。我对 python 很陌生,所以也许我错过了一些东西......但是每次发生错误时,log.txt 都会被覆盖,并且只显示当前的错误消息,尽管错误消息每次都不同(由于时间戳)并且我添加了\n。
到目前为止,这是我的代码:
导入操作系统 导入系统 导入时间 导入日期时间Run Code Online (Sandbox Code Playgroud)尝试: 路径 = sys.argv[1]
ts = time.time() sttime = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d_%H:%M:%S - ') #some more things but nothing else of interest for here except: error = "ERROR! No file 'bla' found!" log = 'log.txt' logfile = file(log, "w") logfile.write(sttime + error + '\n') logfile.close() sys.exit(0)
也许你可以帮我一下。我需要在某处循环吗?我尝试创建一个空字符串(error = ""),每次发生错误时都会使用 += 将错误消息添加到 log.txt 中,但这根本不起作用:-/
谢谢你!
以追加模式打开文件,因为该'w'模式每次都会截断文件。,即
logfile = open(log, "a")
Run Code Online (Sandbox Code Playgroud)
你应该使用with:
with open(log, 'a') as logfile:
logfile.write(sttime + error + '\n')
Run Code Online (Sandbox Code Playgroud)
无需关闭文件,这会自动发生。
请注意,如果在 引发异常path = sys.argv[1],则在您尝试记录时可能不会设置时间戳。最好在日志代码中获取时间戳。
另外,您不应该使用裸except子句,但至少捕获异常并报告它。
from datetime import datetime
except Exception, exc:
sttime = datetime.now().strftime('%Y%m%d_%H:%M:%S - ')
error = "ERROR! {}".format(exc)
log = 'log.txt'
with open(log, 'a') as logfile:
logfile.write(sttime + error + '\n')
raise
# sys.exit(0)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19659 次 |
| 最近记录: |