Tutorials / Python Basics / Lesson 13

Reading and Writing Files

What You Will Learn

So far, your programs forget everything when they stop running. In this lesson, you will learn how to save data to files and read it back later.


Writing to a File

Use open() with mode "w" to write:

with open("notes.txt", "w") as f:
    f.write("Hello, file!\n")
    f.write("This is my second line.\n")

print("File written.")

Expected output:

File written.

After running this, you will find a file called notes.txt in the same folder as your script. Open it and you will see:

Hello, file!
This is my second line.

The with statement automatically closes the file when the block finishes — always use it.

Warning: mode "w" overwrites the file if it already exists. Use "a" (append) to add to an existing file instead.


Reading a File

Use open() with mode "r" to read:

with open("notes.txt", "r") as f:
    content = f.read()

print(content)

Expected output:

Hello, file!
This is my second line.

Reading Line by Line

For large files, read one line at a time:

with open("notes.txt", "r") as f:
    for line in f:
        print(line.strip())

Expected output:

Hello, file!
This is my second line.

.strip() removes the newline character at the end of each line.


Reading All Lines as a List

with open("notes.txt", "r") as f:
    lines = f.readlines()

print(lines)
print(f"Total lines: {len(lines)}")

Expected output:

['Hello, file!\n', 'This is my second line.\n']
Total lines: 2

Appending to a File

Mode "a" adds to the end without overwriting:

with open("notes.txt", "a") as f:
    f.write("This line was added later.\n")

A Practical Example: Simple To-Do List

FILE = "todo.txt"

def load_tasks():
    try:
        with open(FILE, "r") as f:
            return [line.strip() for line in f if line.strip()]
    except FileNotFoundError:
        return []

def save_tasks(tasks):
    with open(FILE, "w") as f:
        for task in tasks:
            f.write(task + "\n")

tasks = load_tasks()

while True:
    print(f"\nTasks ({len(tasks)} total):")
    for i, task in enumerate(tasks, 1):
        print(f"  {i}. {task}")

    action = input("\nAdd (a), Done (d), Quit (q): ")

    if action == "a":
        task = input("New task: ")
        tasks.append(task)
        save_tasks(tasks)
    elif action == "d":
        num = int(input("Task number: ")) - 1
        removed = tasks.pop(num)
        save_tasks(tasks)
        print(f"Removed: {removed}")
    elif action == "q":
        break

This to-do list saves to a file, so your tasks persist even after the program closes.


What You Learned

  • open(filename, mode) opens a file
  • Mode "w" writes (overwrites), "r" reads, "a" appends
  • Always use with open(...) as f: to ensure the file is closed
  • .read() gets all content, .readlines() gets a list of lines
  • Loop over a file object to read line by line

In the next lesson, you will learn how to handle errors so your programs do not crash unexpectedly.