轻松python之文件专题-关于行的操作
1.计算文本行数最常用的就是readlines
>>> handler=open('input_file.txt')
>>> lines=handler.readlines ()
>>> lenOfFile=len(lines)
但是如果是一个超过100m的文本文件,上面的方法基本确定是会很慢,甚至运行不了 因此,我们需要其他的方法
1)使用循环计数,引入enumerate方法
>>> count=-1
>>> for index,line in enumerate(open ('input_file.txt' , 'rU' )):
count+=1
>>> count
5
>>>
注意:count是从-1开始
2)如果再考虑到性能的问题,我们使用其他的方法
因为文本文件一般已/n为换行符,所以,我们可以载入一部分文本,计算里面的换行符是多少
>>> import codecs
>>> count = 0
>>> the_file = codecs.open('input_file.txt', 'rb', 'utf-8')
>>> try:
while (True):
buffer = the_file.read(8192*1024)
if not buffer:break
count += buffer.count('\n')
finally:the_file.close()
>>> count
5
>>>
2.读取某一行(以小文本为例)
我们一般会想到循环,然后到某一行停下来,打印
>>> handler=open('input_file.txt')
>>> lines=handler.readlines ()
>>> lenOfFile=len(lines)
>>> for x in range(lenOfFile):
if x==3:print(lines)
dff
>>> 上面的例子我们可以封装成一个方法:
>>> def readTheXLineOfFile(path,lineNum):
handler=open(path)
try:
lines=handler.readlines()
for x in range(len(lines)):
if x==lineNum:
print(lines)
finally:handler.close ()
>>> readTheXLineOfFile('input_file.txt',3)
dff
>>>
但是我们有更加快捷的方法:
>>> import linecache
>>> theLine=linecache.getline
>>> theLine=linecache.getline ('input_file.txt',3)
>>> theLine
'bd\n'
>>> theLine=linecache.getline ('input_file.txt',4)
>>> theLine
'dff\n'
>>> 我们引入linecache,通过getline的方法得到某一行,但是需要注意:它的行数是从0开始的
就说到这里,谢谢大家
------------------------------------------------------------------
点击跳转零基础学python-目录
版权声明:本文为博主原创文章,未经博主允许不得转载。
页:
[1]