To count the lines in a file, loop over the file and add 1 for each line. This reads one line at a time, so it also works for very large files.
The program
python
with open("story.txt", "w", encoding="utf-8") as f: f.write("Margaret wrote the code.\n") f.write("The code went to the Moon.\n") f.write("The landing was a success.\n") with open("story.txt", encoding="utf-8") as f: line_count = sum(1 for line in f) print(f"Lines: {line_count}")
output
Lines: 3
How it works
sum(1 for line in f)gives 1 for every line in the file and adds them up. It is the same as a loop withcount += 1.- The common version,
len(f.readlines()), gives the same answer, butreadlines()first builds a list of every line in memory. For a small file that is fine; for a file of several gigabytes it is not. - A last line without a
\nat the end still counts as a line.
Lines, words and characters
The Unix command wc prints these three numbers. Here is the same thing in Python:
python
with open("story.txt", "w", encoding="utf-8") as f: f.write("Margaret wrote the code.\n") f.write("The code went to the Moon.\n") f.write("The landing was a success.\n") lines = words = chars = 0 with open("story.txt", encoding="utf-8") as f: for line in f: lines += 1 words += len(line.split()) chars += len(line) print(f"Lines: {lines}, words: {words}, characters: {chars}")
output
Lines: 3, words: 15, characters: 79
line.split() with no argument splits on any run of spaces and ignores the \n, so it gives the words of the line. The character count includes the three \n characters.