How to get line count cheaply in Python?
I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?At the moment I do: def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1is it possible to do any better?
Nima M.
answered 11/16/19
Python / Java: Object-oriented design, algorithm, data structure
It might be useful to read a block of data from the file and then count the lines in each block:
def blocks(files, size=65536):
while True :
b = files.read(size)if not b: breakyield b
with open("file" , "r" ,encoding="utf-8" ,errors='ignore' ) as f:
print (sum(bl.count("\n" ) for bl in blocks(f)))
Still looking for help? Get the right answer, fast.
OR
Find an Online Tutor Now
Choose an expert and meet online.
No packages or subscriptions, pay only for the time you need.
¢
€
£
¥
‰
µ
·
•
§
¶
ß
‹
›
«
»
<
>
≤
≥
–
—
¯
‾
¤
¦
¨
¡
¿
ˆ
˜
°
−
±
÷
⁄
×
ƒ
∫
∑
∞
√
∼
≅
≈
≠
≡
∈
∉
∋
∏
∧
∨
¬
∩
∪
∂
∀
∃
∅
∇
∗
∝
∠
´
¸
ª
º
†
‡
À
Á
Â
Ã
Ä
Å
Æ
Ç
È
É
Ê
Ë
Ì
Í
Î
Ï
Ð
Ñ
Ò
Ó
Ô
Õ
Ö
Ø
Œ
Š
Ù
Ú
Û
Ü
Ý
Ÿ
Þ
à
á
â
ã
ä
å
æ
ç
è
é
ê
ë
ì
í
î
ï
ð
ñ
ò
ó
ô
õ
ö
ø
œ
š
ù
ú
û
ü
ý
þ
ÿ
Α
Β
Γ
Δ
Ε
Ζ
Η
Θ
Ι
Κ
Λ
Μ
Ν
Ξ
Ο
Π
Ρ
Σ
Τ
Υ
Φ
Χ
Ψ
Ω
α
β
γ
δ
ε
ζ
η
θ
ι
κ
λ
μ
ν
ξ
ο
π
ρ
ς
σ
τ
υ
φ
χ
ψ
ω
ℵ
ϖ
ℜ
ϒ
℘
ℑ
←
↑
→
↓
↔
↵
⇐
⇑
⇒
⇓
⇔
∴
⊂
⊃
⊄
⊆
⊇
⊕
⊗
⊥
⋅
⌈
⌉
⌊
⌋
〈
〉
◊