Editor

Lines, Words and Characters

#543 · File handling · Beginner · 30 XP · about 6 min

Write file_stats(filename) that opens the text file filename, reads it and returns a tuple (lines, words, characters):

  • lines is how many lines the file has. A last line with no newline at its end still counts, and a blank line counts too.
  • words is how many words it has, where words are separated by spaces or line breaks.
  • characters is how many characters it holds, counting every space and every newline character.

Example

If poem.txt holds these three lines, each ending with a newline:

The rain in Spain
falls mainly
on the plain

then file_stats('poem.txt') returns (3, 9, 44). The three lines have 41 letters and spaces between them, plus 3 newline characters.

Note

An empty file gives (0, 0, 0).

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.