python linecache 模組讀取檔案

2021-07-24 03:40:32 字數 1425 閱讀 7459

python linecache 模組讀取檔案用法詳解

linecache 模組允許從任何檔案裡得到任何的行,並且使用快取進行優化,常見的情況是從單個檔案讀取多行。

linecache.getlines(filename)

從名為 filename 的檔案中得到全部內容,輸出為列**式,以檔案每行為列表中的乙個元素,並以 linenum-1 為元素在列表中的位置儲存

linecache.getline(filename,lineno)

從名為 filename 的檔案中得到第 lineno 行。這個函式從不會丟擲乙個異常–產生錯誤時它將返回」(換行符將包含在找到的行裡)。

如果檔案沒有找到,這個函式將會在 sys.path 搜尋。

linecache.clearcache()

清除快取。如果你不再需要先前從 getline() 中得到的行

linecache.checkcache(filename)

檢查快取的有效性。如果在快取中的檔案在硬碟上發生了變化,並且你需要更新版本,使用這個函式。如果省略 filename,將檢查快取裡的所有條目。

linecache.updatecache(filename)

更新檔名為 filename 的快取。如果 filename 檔案更新了,使用這個函式可以更新 linecache.getlines(filename)返回的列表。

用法舉例:

# cat a.txt

1a2b

3c4d

5e6f

7g

1、獲取 a.txt 檔案的內容

>>> a=linecache.getlines('a.txt')

>>> a

['1a\n', '2b\n', '3c\n', '4d\n', '5e\n', '6f\n', '7g\n']

2、獲取 a.txt 檔案中第 1-4 行的內容

>>> a=linecache.getlines('a.txt')[0:4]

>>> a

['1a\n', '2b\n', '3c\n', '4d\n']

3、獲取 a.txt 檔案中第4行的內容

>>> a=linecache.getline('a.txt',4)

>>> a

'4d\n'

此時有兩種方法:

這個模組是使用記憶體來快取你的檔案內容,所以需要耗費記憶體,開啟檔案的大小和開啟速度和你的記憶體大小有關係。

Python linecache模組讀取檔案

linecache 過往在讀取檔案的時候,我們通常使用的是這種模式 with open file.txt r as f line f.readline while line print line 一些行級別的處理 line f.readline 這麼做的好處在於通過一行一行讀取內容,不會一下子把整個...

Python linecache模組讀取檔案

linecache 過往在讀取檔案的時候,我們通常使用的是這種模式 with open file.txt r as f line f.readline while line print line 一些行級別的處理 line f.readline 這麼做的好處在於通過一行一行讀取內容,不會一下子把整個...

讀取Structs properties檔案

在這裡我直接返回的是properties物件 這樣更靈活 可以在外部呼叫的時候想哪到properties檔案裡的哪個屬性都行,當然必須要是properties裡存在的。讀取properties檔案 param propertiesname return public static propertie...