[英]python read log and write to new file
im using the following code to read file , and write some lines which contain certain word 即时通讯使用以下代码读取文件,并写一些包含某些单词的行
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()
I still cant get the file created and data inserted , what do i miss here ? 我仍然无法创建文件并插入数据,我在这里想念什么?
You keep overwriting using w
use a
to append or open outside the loop. 您可以使用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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.