Python linecache模組

來源:互聯網
上載者:User

linecache

今天分享一個python的小模組: linecache, 可以用它方便地擷取某一檔案某一行的內容。而且它也被 traceback 模組用來擷取相關源碼資訊來展示。
用法很簡單:

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

linecache.getline 第一參數是檔案名稱,第二個參數是行編號。如果檔案名稱不能直接找到的話,會從 sys.path 裡找。

如果請求的行數超過檔案行數,函數不會報錯,而是返回''Null 字元串。如果檔案不存在,函數也不會報錯,也返回''Null 字元串。

linecache 會嘗試用緩衝一些資訊來最佳化對檔案的讀取。它還提供了兩個方法來處理緩衝相關。

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

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.