python計算文件行數的三種方法


## 小文件
#file=r"c:\users\zm.com\desktop\20140106.txt"
#count=len(open(file,'ru').readlines())
#print(count)

##大文件
#file=r"C:\Users\zm.com\Desktop\20140224.txt"
#count=-1
#for count,line in enumerate(open(file,'rU').readlines()):
#    count += 1
#print(count)

#利用統計換行符數量的方法(不太適應於一些沒有標題的數據文本,因為開頭第一行並沒有換行符,所以讀只有一行的數據,count==1)
file=r"C:\Users\zm.com\Desktop\20140224.txt"
count=1 #第一行沒有換行符
opfile=open(file,'rb')
while True:
    buffer=opfile.read(8192*1024)
    if not buffer:
        break
    buffer=buffer.decode()
    count += buffer.count('\n ')
opfile.close()
print(count)

filename=r"C:\Users\zm.com\Desktop\N20140224.txt"
with open(filename,'w')as f:
    f.writelines(["20140224:",",",str(count)])

參考鏈接:https://blog.csdn.net/shandong_chu/article/details/70173952

翻譯 朗讀 復制 正在查詢,請稍候…… 重試 朗讀 復制 復制 朗讀 復制 via 谷歌翻譯(國內)


免責聲明!

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



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