简体   繁体   English

从文件中读取行并选择python

[英]Reading lines from a file and selecting a python

the problem is, there is a log file that contains: path /var/log/iptraf/logi 问题是,有一个日志文件包含:path / var / log / iptraf / logi

Fri Mar 23 12:42:19 2012; TCP; eth0; 52 bytes; 
Fri Mar 23 12:43:21 2012; TCP; eth0; 52 bytes; 
Fri Mar 23 12:44:28 2012; TCP; eth0; 52 bytes; 
Fri Mar 23 12:45:29 2012; TCP; eth0; 52 bytes;
Fri Mar 23 12:46:30 2012; TCP; eth0; 52 bytes; 
Fri Mar 23 12:47:31 2012; TCP; eth0; 52 bytes;

I need to know the traffic spent the last two minutes of the date of this Code 我需要知道此守则日期的后两分钟所花费的流量

#!/usr/bin/env python
#-*- coding: utf-8 -*-
import re, sys, datetime

cutoff = datetime.datetime.now() - datetime.timedelta(minutes=2)
timestr = str(cutoff)[11:19]

# Open files:
data = open('/var/log/iptraf/logi', 'r')
output = open('/var/log/iptraf/logs', 'w')
dd=data.find('timestr')
output.write("%s" %dd)

But i got mistake 但是我错了

dd=data.find('timestr')
AttributeError: 'file' object has no attribute 'find'

how do I optimize the code so that he was looking for a string in the last two minutes and wrote down traffic like this in other file /var/log/iptraf/logs 我如何优化代码,以便他在最近两分钟内寻找一个字符串,并在其他文件/ var / log / iptraf / logs中写下这样的流量

Fri Mar 23 12:46:30 2012; TCP; eth0; 52 bytes; 
Fri Mar 23 12:47:31 2012; TCP; eth0; 52 bytes;

Indeed, the open() function does not return a String. 实际上, open()函数不会返回String。 Rather, it returns a File . 而是返回File Files are iterable, so it would be possible to consider every line like this: 文件是可迭代的,因此可以考虑如下每一行:

for line in data:
    if timestr in line:
        output.write(line)

Thing is, your most recent times will be at the end of your log file, so to save time you'd rather read backwards. 事实是,您的最近时间将在日志文件的末尾,因此为了节省时间,您宁愿向后阅读。 I recommend taking a look at this page from the Python Cookbook for a nice way to do that. 我建议您查看Python Cookbook上的此页面,这是一种不错的方法。

open doesn't return a string. open不返回字符串。 Use data.read().find('timestr') if you're OK with reading the whole file at once. 如果可以一次读取整个文件, data.read().find('timestr')使用data.read().find('timestr') If not, I'd suggest a loop, see http://www.yak.net/fqa/171.html 如果没有,我建议循环,请参阅http://www.yak.net/fqa/171.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM