Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python读取日志并写入新文件_Python_Python 2.7 - Fatal编程技术网

python读取日志并写入新文件

python读取日志并写入新文件,python,python-2.7,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

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

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()
我仍然无法创建文件并插入数据,
我在这里遗漏了什么?

您使用
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)          

您可以使用
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)          

您是否检查了
.py
文件所在的根目录?它应该在那里。您是否检查了
.py
文件所在的根目录?它应该在那里。@Jecki,没有问题,在循环外打开一次是最好的选择。@Jecki,没有问题,在循环外打开一次是最好的选择。