python读取日志并写入新文件

时间:2015-04-14 08:28:29

标签: python python-2.7

我使用以下代码来读取文件,并写一些包含某些单词的行

with open('access.log') as f:
    for line in f:
         logdate = datetime.strptime(line.split(',')[0], '%Y-%m-%d %H:%M:%S')
         if logdate >= datetime.now() - timedelta(minutes=10):
             if 'Busy' in line:
                 file = open ('newfile.txt' , 'w')
                 file.write(line)
                 file.close()

我仍然无法创建文件并插入数据, 我在这里想念什么?

1 个答案:

答案 0 :(得分:4)

使用w使用a覆盖或在循环外打开,继续覆盖。

with open('access.log') as f, open ('newfile.txt' , 'w') as file:
    for line in f:
         logdate = datetime.strptime(line.split(',')[0], '%Y-%m-%d %H:%M:%S')
         if logdate >= datetime.now() - timedelta(minutes=10) and 'Busy' in line:
                 file.write(line)