用时间戳+消息写入文件行

时间:2014-10-09 10:23:16

标签: python python-2.7

我想创建一个日志文件,每次向文本文件log.txt发送新行时都会添加该日志文件。我是python的新手,所以也许我会错过一些东西......但是每次发生错误时,都会覆盖log.txt并且只显示当前的错误消息,尽管错误消息每次都不同(由于时间戳)而我添加了\ n。

到目前为止我的代码:

import os
import sys
import time
import datetime

try: path = 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)

也许你可以帮助我。我需要在某个地方使用循环吗?我试图创建一个空字符串(错误=""),每次发生错误时都会将错误消息添加到log.txt并带+ =但这根本不起作用: - /

谢谢!

3 个答案:

答案 0 :(得分:4)

以附加模式打开文件,因为'w'模式每次都会截断文件。,即

logfile = open(log, "a")

你应该使用with

with open(log, 'a') as logfile:
    logfile.write(sttime + error + '\n')

无需关闭文件,这将自动发生。

请注意,如果在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)

答案 1 :(得分:1)

当你做文件时(日志,' W')。文件日志将变为空。如果你想添加一些东西,你应该使用a而不是w:

open(log, "a")

答案 2 :(得分:-1)

class Logger(object):
    def __init__(self, n):
        self.n = n 
        self.count = 0 
        self.log = open('log.txt', 'a')


    def write(self, message):
        self.count+=1
        if self.count<self.n:
            self.log.write("%s %s"% (time,message))
            self.log.flush()
import sys
sys.stdout= Logger()

时间 - 是按照您想要的方式格式化时间字符串。

现在常规打印功能将写入文件。

相关问题