Count the lines in a log file
Problem statement
Read the file app.log from the current folder and print how many lines it has, in the format:
app.log has 5 lines
Examples
Example 1
Input: app.log contains:
2026-09-24 10:00:01 INFO service started
2026-09-24 10:02:15 INFO request handled in 120ms
2026-09-24 10:05:42 ERROR database connection refused
2026-09-24 10:06:10 WARNING slow response 2300ms
2026-09-24 10:07:55 ERROR disk full on /var
Output: app.log has 5 lines
Hints
Approach
Optimal
open() returns a file object, and the with ... as f: form guarantees the file is closed when the block ends, even if an error happens. Looping over f yields the file one line at a time, which works for huge logs because Python never loads the whole file into memory. The loop uses the counter pattern: start at 0 and add 1 per line. Passing encoding="utf-8" avoids surprises on Windows, where the default encoding differs.
filename = "app.log" count = 0with open(filename, encoding="utf-8") as f: for line in f: count += 1 print(f"{filename} has {count} lines")Follow-up questions
- Count only the lines that contain
ERROR. - Skip blank lines when counting, using
if line.strip():.
Frequently asked questions
It reads the whole file into memory, and if the file ends with a newline (as most do) it counts one extra empty piece. Looping line by line is both more accurate and safer for large files.
Python looks for the file relative to the folder you ran the script from, not where the script is saved. cd into the folder with the log, or use the full path.