Skip to content
IT Vizag
← Files, Modules & Packages

Reading and writing text files

Lesson 1 of 10 · 2 min read

Open, read, write and the with statement.

🎬 Video version coming soon — read it now

Until now, everything your program knew disappeared when it stopped. Files let your program remember: save results, load settings, read data someone else created.

Writing a file

with open("notes.txt", "w") as f:
    f.write("Day 1: learned variables\n")
    f.write("Day 2: learned loops\n")
  • open(name, mode) opens a file. Mode "w" means write: create the file, or replace it if it exists.
  • \n is a new-line character. write() doesn't add one for you.
  • In Colab, click the folder icon on the left to see notes.txt appear.

The with statement

with ... as f: closes the file automatically when the block ends, even if an error happens. Always use it. Unclosed files can lose data.

Reading a file

with open("notes.txt") as f:
    content = f.read()        # the whole file as one string
print(content)

Reading line by line is better for big files:

with open("notes.txt") as f:
    for line in f:
        print(line.strip())   # strip removes the \n at the end

Appending

Mode "a" adds to the end instead of replacing:

with open("notes.txt", "a") as f:
    f.write("Day 3: learned files\n")

The three modes to remember

  • "r": read (the default). Error if the file doesn't exist.
  • "w": write. Erases existing content first.
  • "a": append. Adds to the end.

Opening the wrong file with "w" destroys it, so double-check before running.

Telugu and emoji: use UTF-8

with open("greeting.txt", "w", encoding="utf-8") as f:
    f.write("నమస్కారం Vizag 🌊")

Adding encoding="utf-8" avoids strange characters and errors with non-English text, especially on Windows.

Tip: Colab's files are deleted when the session ends. To keep them, mount Google Drive (folder icon → Mount Drive) and save under /content/drive/MyDrive/.

In one line

Use with open(name, mode) to read ("r"), write ("w") or append ("a") files, and add encoding="utf-8" for Indian languages.

Saved on this device. Sign in to keep progress everywhere.

Share with a friend