python數文件行數最簡單的方法是使用enumerate方法,但是如果文件很大的話,這個方法就有點慢了,我們可以逐塊的讀取文件的內容,然後按塊來數塊內的\n數,從而確定行數。
如下實現代碼:
def blocks(file, size=65536):
while True:
b = files.read(size)
if not b: break
yield b
with open("file", "r") as f:
print sum(bl.count("\n") for bl in blocks(f))