一、linecache模块
我之所以写这个,主要是我需要分析日志文件,但是我不想用到那个实时的日志文件分析,而是定时分析日志文件,故需要反复的使用一个文件进行读取操作,优先考虑这种方式把文件对象当成缓存,下次就不需要从头开始读取了。相比open()那种方法要快N倍,它是你读取文件的效率之源。
linecache模块的作用是将文件内容读取到内存中,进行缓存,而不是每次都要从硬盘中读取,这样效率提高很多,又省去了对硬盘IO控制器的频繁操作。
模块linecache(行-缓存),这对于读取内容非常多的文件,效果甚好,而且它还可以读取指定的行内容。
二、linecache模块函数讲解
1 )、 linecache.getline(filename, lineno[, module_globals]) ,这个方法从filename也就是文件中读取内容,得到第 lineno行,注意没有去掉换行符,它将包含在行内。
2 )、 linecache.clearcache() ,清除现有的文件缓存。
3 )、 linecache.checkcache([filename]) ,参数是文件名,作用是检查缓存内容的有效性,可能硬盘内容发生了变化,更新了,如果不提供参数,将检查缓存中所有的项。
# coding=utf-8
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()
import linecache
file=open(‘3_2.txt’,‘r’)
linecount=len(file.readlines())
linecache.getline(‘3_2.txt’,linecount)
转载:https://blog.csdn.net/wsp_1138886114/article/details/104639191
查看评论