目录
场景:设有A、B两个日志文件,A为t-1时刻的文件,B为t时刻的,日志采用增量方式(随着时间越来越大)。
需求:定期分析当前日志中上一小时的部分,即(B-A)部分
采用方法:获取A的行数(假设500),获取B的行数(假设1000),提取出501~1000行的内容
代码(因服务器环境,用的python2实现):
# -*- coding: utf-8 -*-
from itertools import islice
import sys
def main(current_dir, lasthour_dir, new_dir):
print("当前日志:", current_dir)
print("上个小时日志:", lasthour_dir)
print("生成文件:", new_dir)
# 获取上个小时日志行数
count1 = 0
file1 = open(lasthour_dir, "r")
while True:
buffer = file1.read(1024*8192)
if not buffer:
break
count1 += buffer.count('\n')
file1.close()
print('上个小时日志行数:', count1)
# 获取当前小时日志行数
count2 = 0
file2 = open(current_dir, "r")
while True:
buffer = file2.read(1024*8192)
if not buffer:
break
count2 += buffer.count('\n')
file2.close()
print('当前小时日志行数:', count2)
# 保存增量数据至新文件中
f = open(current_dir, "r")
new = open(new_dir, "w+")
for a in islice(f, count1, count2):
new.write(a)
f.close()
new.close()
main(sys.argv[1], sys.argv[2], sys.argv[3])
python获取一个文件的行数
#encoding=utf-8
#文件比较小
count=len(open(r"train.data",'r').readlines())
print(count)
#文件比较大
count=-1
for count, line in enumerate(open(r"train.data",'r')):
pass
count+=1
print(count)
#更好的方法
count=0
thefile=open("train.data")
while True:
buffer=thefile.read(1024*8192)
if not buffer:
break
count+=buffer.count('\n')
thefile.close()
print(count)
Python3实现从文件中读取指定行的方法
python islice()
islice()获取迭代器的切片,消耗迭代器
语法:
islice(iterable, [start, ] stop [, step]):
from itertools import islice
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
a_ite = iter(a)
print(list(islice(a_ite,0,3)))
print(list(islice(a_ite,0,3)))
print(list(islice(a_ite,0,3)))
linecache.getline
# count = linecache.getline(filename,linenum)
# Python的标准库linecache模块非常适合这个任务
import linecache
the_line = linecache.getline('d:/FreakOut.cpp', 222)
print (the_line)
# linecache读取并缓存文件中所有的文本,
# 若文件很大,而只读一行,则效率低下。
# 可显示使用循环, 注意enumerate从0开始计数,而line_number从1开始
def getline(the_file_path, line_number):
if line_number < 1:
return ''
for cur_line_number, line in enumerate(open(the_file_path, 'rU')):
if cur_line_number == line_number-1:
return line
return ''
the_line = linecache.getline('d:/FreakOut.cpp', 222)
print (the_line)