如何以最有效的内存和时间方式获取大文件的行数?
def file_len(filename):
with open(filename) as f:
for i, _ in enumerate(f):
pass
return i + 1
如何以最有效的内存和时间方式获取大文件的行数?
def file_len(filename):
with open(filename) as f:
for i, _ in enumerate(f):
pass
return i + 1
当前回答
如果你想在Linux下的Python中廉价地获取行数,我推荐这个方法:
import os
print os.popen("wc -l file_path").readline().split()[0]
File_path可以是抽象文件路径,也可以是相对路径。希望这能有所帮助。
其他回答
下面这句话怎么样:
file_length = len(open('myfile.txt','r').read().split('\n'))
用这种方法在一个3900行的文件上计时只需要0.003秒
def c():
import time
s = time.time()
file_length = len(open('myfile.txt','r').read().split('\n'))
print time.time() - s
计数= max(开放(文件))[0]
这个呢
def file_len(fname):
counts = itertools.count()
with open(fname) as f:
for _ in f: counts.next()
return counts.next()
类似的:
lines = 0
with open(path) as f:
for line in f:
lines += 1
如果你的文件中的所有行都是相同的长度(并且只包含ASCII字符)*,你可以非常便宜地执行以下操作:
fileSize = os.path.getsize( pathToFile ) # file size in bytes
bytesPerLine = someInteger # don't forget to account for the newline character
numLines = fileSize // bytesPerLine
*如果使用像é这样的unicode字符,我怀疑需要更多的努力来确定一行中的字节数。