您的位置:首页 > 编程语言 > Python开发

python 读取文件指定某行

2015-12-11 17:51 281 查看
#encoding=utf-8
#从文件中读取某一行 linecache.checkcache可以刷新cache ,linecache可以缓存某一行的信息
import linecache
line = linecache.getline(r'1.txt', 2)
print line
#如果文件比较大 使用下面
def getline(thefilepath,line_num):
if line_num < 1 :return ''
for currline,line in enumerate(open(thefilepath,'rU')):
if currline == line_num -1 : return line
return ''
lines22=getline('1.txt',2)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息