Python open(): Open a File and Choose a File Mode
What Is File Handling in Python?
File handling means your program saves text in a file and reads it back later. A variable forgets its value when the program ends. A file keeps it.
Think of it like the difference between your memory and a notebook. What you keep in your head (a variable) is gone when you fall asleep. What you write in a notebook (a file) is still there tomorrow.
The three steps
Every time you work with a file, you do the same three things:
| Step | What you write | What it does |
|---|---|---|
| 1. Open | open("notes.txt", "w") | finds or makes the file and gets it ready |
| 2. Use | write() or read() | puts text in, or takes text out |
| 3. Close | close() | finishes the work and saves it properly |
- A file has a name, like
notes.txt. The.txtpart says it holds plain text. - A text file holds letters, digits and new lines, nothing else. That's the only kind in this chapter.
Here are all three steps. Run it:
f = open("notes.txt", "w")
f.write("Sunny was here")
f.close()
f = open("notes.txt", "r")
print(f.read())
f.close()Sunny was here
The first part writes a sentence into notes.txt. The second part opens the same file again and reads the sentence back. You'll learn every line of it on this page.
Files in LivePython
LivePython runs Python inside your browser, with a pretend file system kept in memory. So:
- A file your program writes lives only in this browser tab. Reload the page and it's gone.
- Your program can't see or change any file on your real computer. It's a safe place to practise.
- That's why every example in this chapter creates its file first, then reads it. Then it gives the same output every time you run it.
Common beginner doubt: "Where is notes.txt? I can't find it on my computer." It was never there: it lives in the browser's memory. Run the same code with Python on your computer, and you'll find notes.txt in the folder of your program.
File handling lets a program keep text after it ends: open, use, close.