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.
count_nonempty_lines with one parameter, path.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.
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"))
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.