Python linecache模塊

linecache

今天分享一個python的小模塊: linecache, 能夠用它方便地獲取某一文件某一行的內容。並且它也被 traceback 模塊用來獲取相關源碼信息來展現。
用法很簡單:html

>>> import linecache
>>> linecache.getline('/etc/passwd', 4)
'sys:x:3:3:sys:/dev:/bin/sh\n'

linecache.getline 第一參數是文件名,第二個參數是行編號。若是文件名不能直接找到的話,會從 sys.path 裏找。node

若是請求的行數超過文件行數,函數不會報錯,而是返回''空字符串。
若是文件不存在,函數也不會報錯,也返回''空字符串。python

linecache 會嘗試用緩存一些信息來優化對文件的讀取。它還提供了兩個方法來處理緩存相關。windows

linecache.clearcache()   # 清除再也不須要的linecache.getcache()獲取的內容

linecache.checkcache([filename])  # 檢查文件在硬盤上是否有更新,若是有更新緩存。
                                  # 若是沒有提供文件名參數,則檢查linecache緩存裏全部的條目

其它

當文件很大而只要讀取其中一行時,若是採用linecache成爲程序的瓶頸,也能夠採用以下方法來得到速度上一些提高:緩存

def get_line(thefilepath, desired_line_number):
    if desired_line_number < 1: return ''
    for current_line_number, line in enumerate(open(thefilepath, 'rU')):
        if current_line_number == desired_line_number -1:
            return line
    return ''

ps: 打開文件的方式'rU'是以一種windows,mac,unix三個平臺同一的方式打開,都讀取成 n, 參照這裏函數

參考資料

相關文章
相關標籤/搜索