Python3读取UTF-8文件及统计文件行数的方法
本文实例讲述了Python3读取UTF-8文件及统计文件行数的方法。分享给大家供大家参考。具体实现方法如下:
'''''
CreatedonDec21,2012
Python读取UTF-8文件
统计文件的行数目
@author:liury_lab
'''
#-*-coding:utf-8-*-
importcodecs
#对较小的文件,最简单的方法是将文件读入一个行列表中,
#然后计算列表的长度即可
count=len(codecs.open('d:/FreakOut.cpp','rU','utf-8').readlines())
print(count)
#对较大的文件,可循环计数
count=-1
forcount,lineinenumerate(codecs.open('d:/FreakOut.cpp','rU','utf-8')):
pass
count+=1
print(count)
#对于像windows结束标记有'\n'的,还可以有如下办法:
count=0
the_file=codecs.open('d:/FreakOut.cpp','rb','utf-8')
while(True):
buffer=the_file.read(8192*1024)
ifnotbuffer:
break
count+=buffer.count('\n')
count+=1
the_file.close()
print(count)
希望本文所述对大家的Python程序设计有所帮助。