码迷,mamicode.com
首页 > 编程语言 > 详细

python linecache标准库基础学习

时间:2015-03-17 00:42:40      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

#python标准库基础之:linecacge:高效读取文本文件
#说明与作用
"""
可以从文件或者导入python模块获取文件,维护一个结果缓存,从而可以更高效地从相同文件读取多行文本;
此模块会在python标准库的其他部分中用到,缓存实现将在内存中保存文件内容(解析为单独的行
).API通过索引一个列表返回所请求的行。与反复地读取文件并解析文本来查找所需文本行相比,
这样可以节省时间,这个方法在查找同一个文件中多行尤其有用 ,比如一个异常.
"""
import linecache,tempfile,os
#文本,上网或者自己写
# text=‘My father was a self-taught mandolin player. ‘ \
#      ‘He was one of the best string instrument players in our town. ‘ \
#      ‘He could not read music, but if he heard a tune a few times, ‘ \
#      ‘he could play it. When he was younger, he was a member of a small country ‘ \
#      ‘music band. They would play at local dances and on a few occasions ‘ \
#      ‘would play for the local radio station. He often told us how he had ‘ \
#      ‘auditioned and earned a position in a band that featured Patsy Cline as ‘ \
#      ‘their lead singer. He told the family that after he was hired he never ‘ \
#      ‘went back. Dad was a very religious man. He stated that there was a lot ‘ \
#      ‘of drinking and cursing the day of his audition and he did not want to ‘ \
#      ‘be around that type of environment.‘
# def make_file():
#     fd,temp=tempfile.mkstemp()
#     os.close(fd)
#     with open(temp,‘wt‘) as f:
#         try:
#             f.write(‘%s‘%(text))
#         finally:
#             f.close()
#         return temp
#
# def cleanup(filename):
#     os.unlink(filename)

#读取特定的行
#linecache模块读取文件 行号从1开始,不过通常列表数组索引会从0开始
from datatext import *
filename=make_file()
print ‘source:‘
print ‘%r‘%text.split(‘\n‘)[0]
print
print ‘cache:‘
print ‘%r‘%linecache.getline(filename,5)
cleanup(filename)

#处理空行
"""
返回在行末都包括一个换行符,所以如果文本行为空,那么返回值就是一个换行符
"""
print 11
print linecache.getline(filename,2)

#错误处理
#如果所请求的行号走出文件中合法行号范围,getline()会返回空串
not1=linecache.getline(filename,100)
print ‘(%s)‘%(not1,len(not1))

#文件行只有12行,所有请教到第n+1行就像试图超过文件末尾继续读取文件
#读取一个没有存在的文件,也可以使用这样的方法
such_file=linecache.getline(‘a.txt‘)
print u‘无此文件:%s‘%(such_file)

#读取python源文件
"""
由于lincache在生成traceback跟踪记录时使用相当频繁,其关键特性之王就是能够通过指定模块其名在导入路径中查找python源模块!
"""
file_src=linecache.__file__
if file_src.endswith(‘.pyc‘):
    file_src=file_src[:-1]
print ‘\nFILE:‘
with open(file_src,‘r‘)as f:
    file_line=f.readlines()[2]
print repr(file_line)

"""
如果此模块linecache中缓存填充代码在当前目录中无法指定指定名文件,它会在sys.path中搜索指定的模块,这个例子要查找a.py,由于当前目录中
没有这个文件副本,所以会找到标准中相应文件.
"""
#linecache官方标准库地址:https://docs.python.org/2.7/library/linecache.html?highlight=linecache#module-linecache

#lorem ipsum生成器地址如下:http://www.ipsum.com/ #注意:此地址(可能需要FQ或者可能不存在)

 

python linecache标准库基础学习

标签:

原文地址:http://www.cnblogs.com/mhxy13867806343/p/4343349.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!