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

002_005 Python 计算一个文件中有多少行即读取文件行数

2017年11月02日 ⁄ 综合 ⁄ 共 415字 ⁄ 字号 评论关闭

文件D:\123.txt的内容如下:

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

读取文件行数代码如下:

#encoding=utf-8

print '中国'

#计算一个文件中有多少行

#文件比较小
count = len(open(r"d:\123.txt",'rU').readlines())
print count

#文件比较大
count = -1

for count,line in enumerate(open(r"d:\123.txt",'rU')):
    pass
count += 1

print count

#更好的方法
count = 0

thefile = open(r"d:\123.txt",'rb')

while True:
    buffer = thefile.read(1024 * 8192)
    if not buffer:
        break
    count += buffer.count('\n')
thefile.close()

print count

打印结果如下:

中国
6
6
6

抱歉!评论已关闭.