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讀取文件行數大概這三種方法吧,有其他方法歡迎大家指出


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM