livepython.net

175. Python Program to Count Lines and Words in a File

MediumRead

Overview

Count what's in a file with counters and a loop: the counting pattern from the loops chapter, now on a file.

Problem Statement

Read a whole number n, then n lines of text. Write them into a file called story.txt, one per line. Then read the file back, line by line, and print:

  • Lines: and the number of lines that are not empty. A line with only spaces counts as empty.
  • Words: and the number of words in the whole file. Words are separated by spaces.

Your program runs in the browser, so the file lives only in this tab's memory. Create it with "w" before you read it.

Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.

Input

The number of lines, then the lines. Example:

2
Sunny has a cat
Rocky has a big dog

Output

The output for that example:

Lines: 2
Words: 9

The tests try 4 different inputs, some with empty lines.

Learn this firstChapter 19 · Python Read File: read(), readline() and Lines
solution.py
# write your code here

EXPECTED OUTPUT

1Lines: 2
2Words: 9

YOUR OUTPUT

Press Run to see your output here. Lines are compared with the expected output.