How to get the line count of a large file cheaply in Python
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 …