zoukankan      html  css  js  c++  java
  • 如何从一个1G的文件中找到你所需要的东西

    如何从一个1G的文件中找到你所需要的东西,这个问题貌似面试的时候会经常问到。不过不论你用什么语言,肯定逃脱不了按指针读或者按块读。

    这里介绍python的用法。本人亲自实验了,速度还可以。

    如果你的文件还不是很大,那么最好的方式:

    with open('log2.txt') as f:
        for line in f:
            print line.strip()

    貌似这种方式是最快的,不过如果再大点的话,还是比较耗时

    这里有个日志文件,请看格式:

    现在我们想把开始时间为2015-07-18-18:58:00到2015-07-18-18:58:01这段时间的日志快速的筛选出来。

    其实你只要理解文件指针的移动就很会很快有思路。

    fp = open('log.txt')

    fp.tell()文件指针的位置

    fp.seek(0,os.SEEK_END) 文件结尾

    fp.seek(0,os.SEEK_SET) 定位到文件开头

    fp.seek(123,os.SEEK_SET) 定位到指针123的位置

    fp.seek(0,os.SEEK_CUR) 当前指针的位置

    下面是源代码:

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # Author:Eric.yue
    
    import os,time
    
    def find_start_time(start_time,f,size):
        start_point = -1
        seek_point = f.tell()
        #找到开始位置的指针
        while seek_point < size:
             line = f.readline()
             if line.startswith(start_time):
                start_point = seek_point
                break
             seek_point = f.tell()
        return start_point
    
    def find_end_time(end_time,f, size):
        end_point = -1
        seek_point = f.tell()
    
        while seek_point < size:
            line = f.readline()
            if line.startswith(end_time):
                end_point = seek_point
                print 'first end line pos:%s' % line
                break
            #指针移动一定要加上不然会出现死循环
            seek_point = f.tell()
    
        #继续移动指针找到最后一次出现的时间位置
        while seek_point < size:
            line = f.readline()
            if not line.startswith(end_time):
                end_point = seek_point
                print 'last end line pos:%s' % line
                break
            seek_point = f.tell()
    
        return end_point
    
    def read_file(start_point,end_point,fp):
        fp.seek(start_point, os.SEEK_SET)
        while fp.tell() < end_point:
            print fp.readline()
    
    if __name__ == '__main__':
        fp = open('./log','r')
        fp.seek(0,os.SEEK_END)
        #获取文件最后的位置
        size = fp.tell()
        #重新定位到开头
        fp.seek(0, os.SEEK_SET)
    
        s_time = time.time()
        #查找开始时间的位置
        s_point = find_start_time('2015-07-18-18:58:00',fp,size)
        #查找结束时间的位置
        e_point = find_end_time('2015-07-18-18:58:01', fp, size)
        #打印开始时间和结束时间的数据
        read_file(s_point,e_point,fp)
        
        e_time = time.time()
        print 'spend time %s' % (e_time - s_time)
        fp.close()

    OVER!

  • 相关阅读:
    优先队列
    Problem W UVA 662 二十三 Fast Food
    UVA 607 二十二 Scheduling Lectures
    UVA 590 二十一 Always on the run
    UVA 442 二十 Matrix Chain Multiplication
    UVA 437 十九 The Tower of Babylon
    UVA 10254 十八 The Priest Mathematician
    UVA 10453 十七 Make Palindrome
    UVA 10163 十六 Storage Keepers
    UVA 1252 十五 Twenty Questions
  • 原文地址:https://www.cnblogs.com/gide/p/8575403.html
Copyright © 2011-2022 走看看