python 读取标准文件_Python3标准库:linecache高效读取文本文件

1. linecache高效读取文本文件

处理python源文件时,在python标准库的其他部分中用到了linecache模块。缓存实现将在内存中保存文件的内容(解析为单独的行)。这个api通过索引一个list来返回请求的行,与反复的读取文件并解析文本来查找所需文本行相比,这样可以节省时间。这个模块在查找同一个文件中的多行时尤其有用,比如为一个错误报告生成一个跟踪记录(traceback)。

1.1 测试数据

公共数据如下:

import os

import tempfile

import linecache

lorem = '''lorem ipsum dolor sit amet, consectetuer

adipiscing elit. vivamus eget elit. in posuere mi non

risus. mauris id quam posuere lectus sollicitudin

varius. praesent at mi. nunc eu velit. sed augue massa,

fermentum id, nonummy a, nonummy sit amet, ligula. curabitur

eros pede, egestas at, ultricies ac, apellentesque eu,

tellus.

sed sed odio sed mi luctus mollis. integer et nulla ac augue

convallis accumsan. ut felis. donec lectus sapien, elementum

nec, condimentum ac, interdum non, tellus. aenean viverra,

mauris vehicula semper porttitor, ipsum odio consectetuer

lorem, ac imperdiet eros odio a sapien. nulla mauris tellus,

aliquam non, egestas a, nonummy et, erat. vivamus sagittis

porttitor eros.'''

def make_tempfile():

fd, temp_file_name = tempfile.mkstemp()

os.close(fd)

with open(temp_file_name, 'wt') as f:

f.write(lorem)

return temp_file_name

def cleanup(filename):

os.unlink(filename)

filename = make_tempfile()

1.2 读取特定行

linecache模块读取的文件行好从1开始,不过通常列表的数组索引会从0开始。

# pick out the same line from source and cache.

# (notice that linecache counts from 1)

print('source:')

print('{!r}'.format(lorem.split('\n')[4]))

print()

print('cache:')

print('{!r}'.format(linecache.getline(filename, 5)))

cleanup(filename)

返回的各行包括末尾的一个换行符。

1370c0b4aabacf9bac5e16b8d7f30fe0.png

1.3 处理空行

返回值总是在行末尾包含一个换行符,所以如果文本行为空,则返回值就是一个换行符。

# blank lines include the newline

print('blank : {!r}'.format(linecache.getline(filename, 8)))

cleanup(filename)

输入文件的第8行不包含任何文本。

4e6690cd485bf049c7a9c5a2f3b226ef.png

1.4 错误处理

如果所请求的行号超出了文件中合法行号的范围,则getline()会返回一个空串。

# the cache always returns a string, and uses

# an empty string to indicate a line which does

# not exist.

not_there = linecache.getline(filename, 500)

print('not there: {!r} includes {} characters'.format(

not_there, len(not_there)))

输入文件只有15行,所以请求第500行就类似于试图越过文件末尾继续读文件。

5fa3c7fb0f846131cccbb151dccb7ab2.png

读取一个不存在的文件时,也采用同样的方式处理。

# errors are even hidden if linecache cannot find the file

no_such_file = linecache.getline(

'this_file_does_not_exist.txt', 1,

)

print('no file: {!r}'.format(no_such_file))

调用者试图读取数据时,这个模块不会产生异常。

c7a28e1449883b745c2b3ef79b7d5450.png

1.5 读取python源文件

由于生成traceback跟踪记录时linecache使用得非常频繁,其关键特性之一是能够指定模块的基名在导入路径中查找python源模块。

# look for the linecache module, using

# the built in sys.path search.

module_line = linecache.getline('linecache.py', 3)

print('module:')

print(repr(module_line))

# look at the linecache module source directly.

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中搜索指定名的模块。这个例子要查找linecache.py。由于当前目录中没有这个文件副本,所以会找到标准库中相应的文件。

d8c5ac11d7cfab1fb51c88caa9fb078f.png

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值