2022年 11月 4日

python读取文件行数

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

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

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

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

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

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)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

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