我使用以下代码来读取文件,并写一些包含某些单词的行
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()
我仍然无法创建文件并插入数据, 我在这里想念什么?
答案 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)