Stop 06 · Files, Errors & ModulesTopics · 1/9

Reading & Writing Text Files

Part of the Python Roadmap

In short

Variables vanish the moment your program ends. Files are how your code remembers things: notes, logs, reports and settings that are still there tomorrow.

open() gives you a file object in a mode such as 'r' (read), 'w' (overwrite) or 'a' (append). You can read the whole file, read line by line, or write strings, and you should always pass encoding='utf-8'.

The jaadu sits at a desk writing a new line at the end of a thick diary, with an older diary open beside it for reading.

Think of it like this

A diary with three ways to open it

You can open your diary to read old pages ('r'), rip out every page and start fresh ('w'), or flip to the end and keep writing ('a'). Python's open() asks the same question: what do you plan to do with this file?

Watch it happen

'w' or 'a'?

Write mode 'w'

  • Creates the file if missing
  • Wipes existing content first
  • Good for fresh reports
  • Dangerous for logs

Append mode 'a'

  • Creates the file if missing
  • Keeps old content
  • Adds to the end
  • Good for logs and diaries

Use 'w' when you want to replace the whole file, and 'a' when every run should add to what's already there.

The big ideas

What you need to know

Pick a mode

'r' reads (the default), 'w' overwrites, 'a' appends, and 'x' creates only if the file doesn't exist yet.

Always set encoding

Pass encoding='utf-8' so Hindi, Tamil or emoji text reads and writes the same on every computer.

Read line by line

for line in f: reads one line at a time, which works even for files bigger than your RAM.

Newlines are yours to add

write() doesn't add a line break. End each line with \n yourself, and use .strip() when reading to remove it.

See it in code

Walk through the code

python
1with open("notes.txt", "w", encoding="utf-8") as f:2    f.write("Buy milk\n")3    f.write("Call Nani\n")4 5with open("notes.txt", "a", encoding="utf-8") as f:6    f.write("Pay rent\n")7 8with open("notes.txt", encoding="utf-8") as f:9    content = f.read()10print(content)11 12with open("notes.txt", encoding="utf-8") as f:13    for number, line in enumerate(f, start=1):14        print(number, line.strip())15 16with open("notes.txt", encoding="utf-8") as f:17    lines = f.read().splitlines()18print(lines)   # ['Buy milk', 'Call Nani', 'Pay rent']

1/5'w' creates notes.txt (or empties it) and writes two lines. Each ends with \n.

Write a fresh file, append to it, then read it back three different ways.

Save yourself the pain

Common mistakes

Oops

Opening a log file with 'w' every time the program starts.

Do this instead

'w' deletes everything first. Use 'a' to keep previous entries.

Oops

Leaving out encoding and getting UnicodeDecodeError on another laptop.

Do this instead

Always pass encoding='utf-8' for text files so behaviour is the same on Windows and Linux.

Oops

Calling f.readlines() on a huge log file.

Do this instead

That loads every line into memory. Loop over the file object instead.

Your mission

Daily journal

~20 min

Quick check

Which mode adds text to the end of an existing file without deleting anything?

Go deeper

  1. 1Write a few lines to notes.txt, then read them back and print them.
  2. 2Loop over a file object directly to process a large file one line at a time.
  3. 3See how 'w' wipes a file while 'a' adds to the end.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge