python 读取和确定文件的行数(txt,xml,csv等文件)

针对,txt,xml,csv等文件

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 读取和确定文件的行数(txt,xml,csv等文件)