← Back to Python, page 2

python-0027 · Easy fresher

Read a text file safely and count word frequencies.

Open files with a with statement so they close automatically, specify encoding='utf-8', and iterate line by line for large files. collections.Counter counts words directly, and pathlib.Path offers convenient read_text and write_text for small files.

Full answer
python
import tempfile
from collections import Counter
from pathlib import Path

path = Path(tempfile.mkdtemp()) / "notes.txt"
path.write_text("Pune rain. Pune traffic!\nrain again\n", encoding="utf-8")

counts = Counter()
with path.open(encoding="utf-8") as f:
    for line in f:
        words = [w.strip(".,!?").lower() for w in line.split()]
        counts.update(words)
print(counts.most_common(2))
print(path.read_text(encoding="utf-8").count("\n"), path.exists())

Output:

text
[('pune', 2), ('rain', 2)]
2 True

The file is written and read with an explicit encoding, since the default depends on the platform. Reading line by line keeps memory use flat for big files. Stripping punctuation and lowercasing makes 'Pune' and 'rain.' count with their other occurrences, so both appear twice. Without with, an exception between open and close would leave the file open. For CSV or JSON, use the csv and json modules instead of splitting text by hand.

python
import tempfile
from collections import Counter
from pathlib import Path

path = Path(tempfile.mkdtemp()) / "notes.txt"
path.write_text("Pune rain. Pune traffic!\nrain again\n", encoding="utf-8")

counts = Counter()
with path.open(encoding="utf-8") as f:
    for line in f:
        words = [w.strip(".,!?").lower() for w in line.split()]
        counts.update(words)
print(counts.most_common(2))
print(path.read_text(encoding="utf-8").count("\n"), path.exists())

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Use with to close files
  • Pass encoding explicitly
  • Iterate lines for large files
  • Counter counts and ranks
  • pathlib simplifies paths and small reads

Common mistakes

  • Forgetting encoding and breaking on Windows
  • Reading huge files with read() into memory

Follow-ups

  • How would you process a 10 GB log file?
  • How do you write a file atomically?

Tips

  • Mention encoding