Processing Lines

Processing Lines

Most text files are processed line by line. Looping over an open file gives one line per pass:

with open("scores.txt") as file:
    for line in file:
        print(line.strip())

Each line includes its trailing newline character, which is why strip appears in almost every line-processing loop — without it, print would add a second newline and the output would be double-spaced.

From here the section's earlier patterns apply directly. Summing a file of numbers is an accumulator over lines:

def total_of(path):
    total = 0
    with open(path) as file:
        for line in file:
            total += int(line.strip())
    return total

A file with the lines 12, 30, 8 gives 50.

Exercise

  1. Define a function named count_nonempty_lines with one parameter, path.
  2. It returns how many lines in the file contain something other than whitespace. A line of spaces counts as empty.

For a file with the lines milk, an empty line, and bread, the result is 2.

Run your code to see the output, then press Submit.

Tests

import unittest


class TestCountNonemptyLines(unittest.TestCase):
    def test_blank_line_is_not_counted(self):
        with open("test_items.txt", "w") as file:
            file.write("milk\n\nbread\n")
        self.assertEqual(count_nonempty_lines("test_items.txt"), 2)

    def test_whitespace_only_line_is_not_counted(self):
        with open("test_spaces.txt", "w") as file:
            file.write("a\n   \nb\n")
        self.assertEqual(count_nonempty_lines("test_spaces.txt"), 2)

    def test_empty_file_has_zero_lines(self):
        with open("test_blank.txt", "w") as file:
            file.write("")
        self.assertEqual(count_nonempty_lines("test_blank.txt"), 0)
def count_nonempty_lines(path):
    count = 0
    with open(path) as file:
        for line in file:
            if line.strip() != "":
                count += 1
    return count


with open("items.txt", "w") as file:
    file.write("milk\n\nbread\n")

print(count_nonempty_lines("items.txt"))
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.