python读取文件行数

1.直接调用readlines函数接口:

#文件比较小
count=len(open(r"train.data",'rU').readlines())
print(count)

2.借助循环计算文件行数:

#文件比较大
count=-1
for count, line in enumerate(open(r"train.data",'rU')):
        count+=1
print(count)

3.计算缓存中回车换行符的数量,效率较高,但不通用

#更好的方法
count=0
thefile=open("train.data")
while True:
    buffer=thefile.read(1024*8192)
    if not buffer:
        break
    count+=buffer.count('\n')
thefile.close()
print(count)

python读取文件行数大概这三种方法吧,有其他方法欢迎大家指出