One line, faster than the for
loop of the OP (although not the fastest) and very concise:
num_lines = sum(1 for _ in open('myfile.txt'))
You can also boost the speed (and robustness) by using rbU
mode and include it in a with
block to close the file:
with open("myfile.txt", "rbU") as f:
num_lines = sum(1 for _ in f)
Note: The U
in rbU
mode is deprecated since Python 3.3 and above, so iwe should use rb
instead of rbU
(and it has been removed in Python 3.11).