python读取大文件内容_Python模块linecache处理大文件
linecache模塊簡介
Python處理大文件需要用到Linecache模塊。
linecache模塊的作用是將文件內(nèi)容讀取到內(nèi)存中,進行緩存,而不是每次都要從硬盤中讀取,這樣效率提高很多,又省去了對硬盤IO控制器的頻繁操作。linecache的緩存機制,對于讀取內(nèi)容非常多的文件,效果甚好,而且它還可以讀取指定的行內(nèi)容。
linecache常用函數(shù)
linecache.getline(filename, lineno[, module_globals])
1
linecache.getline(filename,lineno[,module_globals])
這個方法從filename也就是文件中讀取內(nèi)容,得到第 lineno行,注意沒有去掉換行符,它將包含在行內(nèi)。
linecache.clearcache()
1
linecache.clearcache()
清除現(xiàn)有的文件緩存。
linecache.checkcache([filename])
1
linecache.checkcache([filename])
參數(shù)是文件名,作用是檢查緩存內(nèi)容的有效性,可能硬盤內(nèi)容發(fā)生了變化,更新了,如果不提供參數(shù),將檢查緩存中所有的項。
示例代碼
讀取本地一個大文件,并以字符串形式打印在屏幕上。
# coding=utf-8
# auth www.py40.com
import os
import linecache
def get_content(path):
'''讀取緩存中文件內(nèi)容,以字符串形式返回'''
if os.path.exists(path):
content = ''
cache_data = linecache.getlines(path)
for line in range(len(cache_data)):
content += cache_data[line]
return content
else:
print('the path [{}] is not exist!'.format(path))
def main():
path = 'c:\\test.txt'
content = get_content(path)
print(content)
if __name__ == '__main__':
main()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# coding=utf-8
# auth www.py40.com
importos
importlinecache
defget_content(path):
'''讀取緩存中文件內(nèi)容,以字符串形式返回'''
ifos.path.exists(path):
content=''
cache_data=linecache.getlines(path)
forlineinrange(len(cache_data)):
content+=cache_data[line]
returncontent
else:
print('the path [{}] is not exist!'.format(path))
defmain():
path='c:\\test.txt'
content=get_content(path)
print(content)
if__name__=='__main__':
main()
總結
以上是生活随笔為你收集整理的python读取大文件内容_Python模块linecache处理大文件的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 流畅、稳定全面进化:魅族Flyme 10
- 下一篇: pytorch reshape_PyTo