6.5.4 错误处理
如果所请求的行号超出了文件中合法行号的范围,则getline()会返回一个空串。
import linecache
from linecache_data import *
filename = make_tempfile()
# The cache always returns a string,and uses
# an empty string to indicate a line that does
# not exist.
not_there = linecache.getline(filename,500)
print('Not THERE: {!r} includes {} characters'.format(
not_there,len(not_there)))
cleanup(filename)
输入文件只有15行,所以请求第500行就类似于试图越过文件末尾继续读文件。
运行结果:
Not THERE: ‘’ includes 0 characters
读取一个不存在的文件时,也采用同样的方式处理。
import linecache
# Error 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))
调用者试图读取数据时,这个模块不会产生异常。
运行结果:
NO FILE:’’