Skip to content

Working with Files

Programming Python Difficulty 1/5

Beginning of the lesson

Working with Files

Save your program's data and read it back later

Big Idea: A variable disappears when your program stops. A file lets your program remember things by saving them on the disk, so you can read them back the next time you run the program.
By the end you will be able to:
  • open a text file with open(),
  • write text to a file and read it back,
  • use the safe with open(...) pattern that closes the file for you.

1. What is a file?

A file is a place on your computer's disk where information is stored with a name, like notes.txt. Unlike a variable, a file stays there even after your program ends or your computer turns off.

Analogy: A variable is like something you hold in your hand — the moment you let go (the program ends), it is gone. A file is like a notebook: you write in it, close it, put it on a shelf, and open it again tomorrow to read what you wrote.

In this topic we work with text files (files full of ordinary characters, like .txt).

2. Open, use, close

To use a file you always do three things in order:

1 2 3 Open the file Read or write Close the file
Every file follows the same three steps: open it, use it, then close it.

You open a file with the built-in open() function. You give it the file name and a mode that says what you want to do:

ModeMeaning
"r"Read an existing file (this is the default).
"w"Write — creates the file, or erases it if it already exists.
"a"Append — adds to the end, keeping what is already there.

When you finish, you must close the file with .close(). Closing saves your changes and frees the file for other programs:

f = open("notes.txt", "w")
f.write("Hello, file!")
f.close()

This works, but it is easy to forget close() — especially if an error happens before you reach it. There is a safer way, coming next.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers