Count the Lines in a Log File

Easy ⏱ 8 min 78% acceptance ★★★★☆ 4.2
Write count_lines(path) that opens a text file and returns how many lines it contains. Use a with statement so the file is always closed, and iterate the file object directly instead of loading everything with read().

Examples

Example 1
Input
count_lines('app.log')  # file has 3 lines
Output
3
Explanation

Iterating a file object yields one line at a time.

Constraints

  • Use a with block.
  • Do not call read() — iterate the file object.

Topics

File Handlingreading

Companies

TCSInfosysIBM

Hints

Hint 1

for line in f: consumes the file lazily.

Hint 2

sum(1 for _ in f) is an idiomatic count.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.