现在的位置: 首页 > 综合 > 正文

002_004 Python 从文件中读取某一行

2017年12月10日 ⁄ 综合 ⁄ 共 423字 ⁄ 字号 评论关闭

D:\123.txt中内容如下:

1abc中国
2abc中国
3abc中国
4abc中国
5abc中国
6abc中国

读取第五行代码如下:

#encoding=utf-8

print '中国'

#从文件中读取某一行 linecache.checkcache可以刷新cache ,linecache可以缓存某一行的信息         
import linecache

theline = linecache.getline(r'd:\123.txt', 5)
print theline

#如果文件比较大 使用下面 
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 ''

print getline(r'd:\123.txt', 5)

打印结果如下:

中国
5abc中国

5abc中国

抱歉!评论已关闭.