Practice · Python

Practice File Basics: Read & Write

Read and write text files using with-statements, and process file contents line by line.

File Basics: Read & Writewarming python…

Count non‑empty lines in a file

Write a function count_nonempty_lines(file_path) that receives the path to a text file, reads it using a with open(..., 'r') block, and returns the number of lines that contain at least one non‑whitespace character. Empty lines or lines that only contain spaces/tabs should not be counted.

Example:

# suppose 'sample.txt' contains:
# Line one\n
#   \n# Line three\n
print(count_nonempty_lines('sample.txt'))  # -> 2
Press Run to see output, or Check to grade against the tests.

Want a whole course built around file basics: read & write?

Start my path — free

Adaptive practice, streaks, projects with real code review. Free tier gates AI help, never content.