文章目录 [ 隐藏 ]
linecache模块简介
Python处理大文件需要用到Linecache模块。
linecache模块的作用是将文件内容读取到内存中,进行缓存,而不是每次都要从硬盘中读取,这样效率提高很多,又省去了对硬盘IO控制器的频繁操作。linecache的缓存机制,对于读取内容非常多的文件,效果甚好,而且它还可以读取指定的行内容。
linecache常用函数
1 |
linecache.getline(filename, lineno[, module_globals]) |
这个方法从filename也就是文件中读取内容,得到第 lineno行,注意没有去掉换行符,它将包含在行内。
1 |
linecache.clearcache() |
清除现有的文件缓存。
1 |
linecache.checkcache([filename]) |
参数是文件名,作用是检查缓存内容的有效性,可能硬盘内容发生了变化,更新了,如果不提供参数,将检查缓存中所有的项。
示例代码
读取本地一个大文件,并以字符串形式打印在屏幕上。
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 import os import linecache def get_content(path): '''读取缓存中文件内容,以字符串形式返回''' 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() |
未经允许不得转载:Python在线学习 » Python模块linecache处理大文件