The Seven Year Itch.

MENU

python 计算一个文件(文本)的行数

March 7, 2017 • Read: 264 • Python

#encoding=utf-8  
  
print '中国'  
  
#计算一个文件中有多少行  
  
#文件比较小使用  
count = len(open(r"d:\123.txt",'rU').readlines())  
print count  
  
#文件比较大使用  
count = -1  
  
for count,line in enumerate(open(r"d:\123.txt",'rU')):  
    pass  
count += 1  
  
print count  
  
#更好的方法  
count = 0  
  
thefile = open(r"d:\123.txt",'rb')  
  
while True:  
    buffer = thefile.read(1024 * 8192)  
    if not buffer:  
        break  
    count += buffer.count('\n')  
thefile.close()  
  
print count  
Tags: None
Archives QR Code
QR Code for this page
Tipping QR Code