讀取檔案指定行linecache

2021-07-04 13:19:08 字數 840 閱讀 5941

import linecache

poem ='''\

programming is fun

when the work is done

if you wanna make your work also fun:

use python!

'''

f = file('poem.txt', 'w')

f.write(poem)

f.close()

file_t = linecache.getline('poem.txt', 6)

print file_t

我們看一下這個模組的名字叫做linecache,行-快取,這對於讀取內容非常多的檔案,效果甚好,而且它還可以讀取指定的行內容。

1 )、 linecache.getline(filename, lineno[, module_globals]) ,這個方法從filename也就是檔案中讀取內容,得到第 lineno行,注意沒有去掉換行符,它將包含在行內。

2 )、 linecache.clearcache() ,清除現有的檔案快取。

3 )、 linecache.checkcache([filename]) ,引數是檔名,作用是檢查快取內容的有效性,可能硬碟內容發生了變化,更新了,如果不提供引數,將檢查快取中所有的項。

linecache裡面最常用到的就是getline方法,簡單實用可以直接從內容中讀到指定的行,日常程式設計中如果涉及讀取大檔案,一定要使用首選linecache模組,相比open()那種方法要快n倍,它是你讀取檔案的效率之源

python讀取檔案指定行

import linecache file open 3 2.txt r linecount len file.readlines linecache.getline 3 2.txt linecount 這樣做的過程中發現乙個問題,因為我的指令碼是迴圈讀取3 2.txt檔案,當3 2.txt發生變化...

python檔案IO 讀取指定行

python的標準庫linecache模組非常適合這個任務 import linecache the line linecache.getline d freakout.cpp 222 print the line linecache讀取並快取檔案中所有的文字,若檔案很大,而唯讀一行,則效率低下。可...

shell awk讀取檔案中的指定行的指定字段

awk指定讀取檔案中的某一行的某個字段 awk 可以設定條件來輸出檔案中m行到n行中每行的指定的k欄位,使用格式如下 awk nr m,nr n path filename m,n,k表示實在的數值。如果要用變數來表示m,n的值,則變數需要用單引號將其引起來。nr,是awk命令在此用法下的規定字段 ...