python打开大日志文件

标签 python

我使用 python 打开大型日志文件,如

Thu Oct  4 23:14:40 2012 [pid 16901] CONNECT: Client "66.249.74.228"
Thu Oct  4 23:14:40 2012 [pid 16900] [ftp] OK LOGIN: Client "66.249.74.228", anon     password "googlebot@google.com"
Thu Oct  4 23:17:42 2012 [pid 16902] [ftp] FAIL DOWNLOAD: Client "66.249.74.228",   "/pub/10.5524/100001_101000/100039/Assembly-2011/Pa9a_assembly_config4.scafSeq.gz",  14811136 bytes, 79.99Kbyte/sec
Fri Oct  5 00:04:13 2012 [pid 25809] CONNECT: Client "66.249.74.228"
Fri Oct  5 00:04:14 2012 [pid 25808] [ftp] OK LOGIN: Client "66.249.74.228", anon password "googlebot@google.com"
Fri Oct  5 00:07:16 2012 [pid 25810] [ftp] FAIL DOWNLOAD: Client "66.249.74.228", "/pub/10.5524/100001_101000/100027/Raw_data/PHOlcpDABDWABPE/090715_I80_FC427DJAAXX_L8_PHOlcpDABDWABPE_1.fq.gz", 14811136 bytes, 79.99Kbyte/sec
Fri Oct  5 00:13:19 2012 [pid 27354] CONNECT: Client "1.202.186.53"
Fri Oct  5 00:13:19 2012 [pid 27353] [ftp] OK LOGIN: Client "1.202.186.53", anon password "mozilla@example.com"

我想像 tail 命令一样从文件末尾读取行以获取最近 7 天 记录。

这是我的代码,我该如何更改。

import time
f= open("/opt/CLiMB/Storage1/log/vsftp.log")
def OnlyRecent(line):
   if  time.strptime(line.split("[")[0].strip(),"%a %b %d %H:%M:%S %Y")>     time.gmtime(time.time()-(60*60*24*7)): 
    return True
return False
filename= time.strftime('%Y%m%d')+'.log'
f1= open(filename,'w')
for line in f:
 if OnlyRecent(line):
        print line
        f1.write(line)
f.close()
f1.close()

最佳答案

使用file.seek()跳转到文件末尾的某个偏移量。例如,要在不读取文件开头的情况下打印文件的最后 1Kb,请执行以下操作:

with open("/opt/CLiMB/Storage1/log/vsftp.log") as f:
     f.seek(-1000, os.SEEK_END)
     print f.read()

关于python打开大日志文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13679063/

相关文章:

python - google.api_core.exceptions.Forbidden : 403 Missing or insufficient permissions

python - 在 matplotlibrc 中设置 bottom, top, left, right tick visibility

python - 尝试从 Jupyter Notebook 使用 Spark 访问 Google Cloud Bigtable 时出现区域错误

python - 无法在 Eclipse 中作为 "PyDev: Django"运行

python - 不要将自定义 setup.py --install-option 传播到依赖项

python - 无法在 Python 中导入 Skype4Py

python - 如何在绘制数据之前删除某些值

python - 使用 PyQt4 - QTableView 与 SQLAlchemy 使用 QSqlTableModel(或不)

python - 如何在plotly 3D中绘制不同高度的多个正方形

python - 这两种基于生成器的协程是同一个概念吗?