[Python]如何取出一個超大文字檔的最後幾行

來源:互聯網
上載者:User
  這是 python-中國 郵件清單中的一個問題。如果不考慮效率問題,這個問題可能很簡單,直接read出整個檔案的內容,然後split一下或者還有更簡單的辦法。但是如果這個檔案是“超大”,那麼為了區區幾行而讀入整個檔案有點‘“得不償失“。下面是我的實現。剛學python不久,也許沒有發揮出它的優點。

#last lines
#by Kevin Yuan
def last_lines(filename, lines = 1):
    #print the last line(s) of a text file
    """
    Argument filename is the name of the file to print.
    Argument lines is the number of lines to print from last.
    """
    block_size = 1024
    block = ''
    nl_count = 0
    start = 0
    fsock = file(filename, 'rU')
    try:
        #seek to end
        fsock.seek(0, 2)
        #get seek position
        curpos = fsock.tell()
        while(curpos > 0): #while not BOF
            #seek ahead block_size+the length of last read block
            curpos -= (block_size + len(block));
            if curpos < 0: curpos = 0
            fsock.seek(curpos)
            #read to end
            block = fsock.read()
            nl_count = block.count('/n')
            #if read enough(more)
            if nl_count >= lines: break
        #get the exact start position
        for n in range(nl_count-lines+1):
            start = block.find('/n', start)+1
    finally:       
        fsock.close()
    #print it out 
    print block[start:]
   
if __name__ == '__main__':
    import sys
    last_lines(sys.argv[0], 5) #print the last 5 lines of THIS file

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.