Is there a Python package that is optimized for determining the number of lines in an ASCII file?
本问题已经有最佳答案,请猛点这里访问。
是否有优化的python包来确定一个大的ascii文件中有多少行而不将整个文件加载到内存中?这与在python中如何以较低的成本获取行计数的主题不同?问题与内置的python解决方案有关。
您可以逐行迭代:
| 1 2 | with open('filename.txt', 'r') as handle: num_lines = sum(1 for line in handle) | 
以更大的块读取它并只计算换行数可能会更快:
| 1 2 3 4 5 6 | with open('filename.txt', 'r') as handle: num_lines = 0 for chunk in iter(lambda: handle.read(1024*1024), None): num_lines += chunk.count(' ') | 
另一种选择是使用
| 1 2 3 4 5 6 7 | import fileinput x = fileinput.input('test.csv') for line in x: pass print x.lineno() 3 x.close() |