第六章:文件系统-linecache:高效读取文本文件-错误处理

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:’’

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值