python开发_linecache

#linecache的名称,我们可以知道该模块和cache(缓存)有关
#linecache现把文件读入到缓存中,在以后访问文件的时候,就不必要再从硬盘读取
#所以经常用于那些读取频率很高的文件
还可以参考:open()

运行效果:

================================================

代码部分:

================================================

 1 #python linecache
 2 
 3 #从linecache的名称,我们可以知道该模块和cache(缓存)有关
 4 #linecache现把文件读入到缓存中,在以后访问文件的时候,就不必要再从硬盘读取
 5 #所以经常用于那些读取频率很高的文件
 6 
 7 import os
 8 import linecache
 9 
10 def get_content(path):
11     '''读取缓存中文件的内容,并以字符串形式返回'''
12     if os.path.exists(path):
13         content = ''
14         cache_data = linecache.getlines(path)
15         for line in range(len(cache_data)):
16             content += cache_data[line]
17         return content
18     else:
19         print('the path [{}] is not exist!'.format(path))
20 
21 def main():
22     path = 'c:\\test.txt'
23     content = get_content(path)
24     print(content)
25 
26 if __name__ == '__main__':
27     main()

 

posted @ 2013-08-16 16:16  Hongten  阅读(3745)  评论(0编辑  收藏  举报
Fork me on GitHub