livepython.net
CHAPTER 19File Handling
19.1  OPEN()

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:

StepWhat you writeWhat it does
1. Openopen("notes.txt", "w")finds or makes the file and gets it ready
2. Usewrite() or read()puts text in, or takes text out
3. Closeclose()finishes the work and saves it properly
  • A file has a name, like notes.txt. The .txt part 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:

PYTHONedit me
f = open("notes.txt", "w")
f.write("Sunny was here")
f.close()

f = open("notes.txt", "r")
print(f.read())
f.close()
OUTPUT
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.

your turnPick the right idea

Why would a program save its data in a file?

Think about it, then pick one.
your turnPredict the output

What will this print?

f = open("pet.txt", "w") f.write("Rocky") f.close() f = open("pet.txt", "r") print(f.read()) f.close()
Your turn! What will this code show on the screen?

Open and Close a File with open() and close()

The open() function opens a file and gives you back a file object: a value that stands for the open file. When you're done, you call its close() method to close the file again.

Think of it like borrowing a book from a library. You take it out (open), read or write in it (use), and bring it back (close). While it's out, it's yours to use. Once it's back, you can't read it any more.

The rules

  • Write open(name, mode): the file name and the mode, both as strings in quotes.
  • Store what open() gives back in a variable. Short names like f or file are usual.
  • Use the file through that variable with a dot: f.write(...), f.read(), f.close(). Like the list methods from chapter 9.
  • Call f.close() as soon as you're done, with the brackets.
PYTHONedit me
f = open("greeting.txt", "w")
f.write("Hello, Lucky!")
f.close()
print("Saved!")

f = open("greeting.txt", "r")
text = f.read()
f.close()
print(text)
OUTPUT
Saved!
Hello, Lucky!

f.read() gives back the text, so you can store it in a variable, like input() gives back what the user types. After f.close(), the text is still safe in text.

Avoid: using a file after closing it

PYTHONedit me
f = open("greeting.txt", "w")
f.write("Hi")
f.close()
f.write("Bye")
OUTPUT
ValueError: I/O operation on closed file.

Don't be scared of this error! I/O means input and output: reading and writing. Python is saying "this file is closed, I can't write to it". Open it again first.

Common mistake: close without brackets

f.close without () gives no error, but it doesn't close anything either. It only names the method. To call a method, you always need the brackets: f.close().

Common beginner doubt: "What if I forget to close?" The text you wrote may not be saved yet. You'll see this happen, and the easy fix, in the with lesson at the end of this chapter.

open() gives you a file object; use it, then close it with close().

your turnSpot the bug

Which line breaks?

One line stops this program. Tap it.
your turnPredict the output

What will this print?

f = open("name.txt", "w") f.write("Sunny") f.close() f = open("name.txt", "r") name = f.read() f.close() print(name + "!")
Your turn! What will this code show on the screen?

Python File Modes: r, w and a

The mode is the second thing you give open(). It's one letter that tells Python what you want to do with the file: read it, write it, or add to it.

Think of it like a notebook again. Mode "r" means you only look at the pages. Mode "w" means you tear out every page and start a fresh one. Mode "a" means you turn to the last page and keep writing there.

The three modes

ModeShort forWhat it doesIf the file is missing
"r"readonly readsFileNotFoundError
"w"writeempties the file, then writesmakes a new, empty file
"a"appendadds at the end, keeps the old textmakes a new, empty file
  • "r" is the default: open("notes.txt") is the same as open("notes.txt", "r").
  • A file opened with "r" can't be written to. A file opened with "w" or "a" can't be read.

All three in one program:

PYTHONedit me
f = open("list.txt", "w")
f.write("Sunny ")
f.close()

f = open("list.txt", "a")
f.write("Rocky")
f.close()

f = open("list.txt", "r")
print(f.read())
f.close()
OUTPUT
Sunny Rocky

"w" starts the file fresh with Sunny , "a" adds Rocky after it, and "r" reads the result.

Avoid: writing to a file opened for reading

PYTHONedit me
f = open("list.txt", "w")
f.write("Sunny")
f.close()

f = open("list.txt")
f.write("Lucky")
OUTPUT
UnsupportedOperation: not writable

open("list.txt") has no mode, so it's "r": read only. Python says the file is "not writable". Choose "w" or "a" when you want to write.

Good: pick the mode for the job

  • Reading what's there? "r".
  • Making a file from scratch, or replacing it? "w".
  • Adding to what's there, like a log or a diary? "a".

Common beginner doubt: "Can I write "read" instead of "r"?" No. Python only knows the short letters. open("list.txt", "read") stops with a ValueError.

"r" reads, "w" starts the file fresh, "a" adds to the end. "r" is the default.

your turnPredict the output

What will this print?

f = open("pets.txt", "w") f.write("cat ") f.close() f = open("pets.txt", "w") f.write("dog") f.close() f = open("pets.txt") print(f.read()) f.close()
Your turn! What will this code show on the screen?
your turnFill the gap

Add Lucky to the end of the file

f = open("team.txt", "w") f.write("Rocky ") f.close() f = open("team.txt", ?) f.write("Lucky") f.close() f = open("team.txt") print(f.read()) f.close()

It should print: Rocky Lucky

Which piece makes this code work?

File Names, Paths and FileNotFoundError

A file name like "notes.txt" tells open() which file you mean. A path is a longer name that also says which folder the file is in, like "school/notes.txt". If you open a file for reading and Python can't find it, you get a FileNotFoundError.

Think of it like a home address. "notes.txt" is "the house next door": Python looks in the same folder as your program. A path is a full address, with the street and the town.

The rules

  • The name is a string, in quotes, with its ending: "notes.txt", not notes.
  • Names must match exactly: "Notes.txt" and "notes.txt" are two different files.
  • In this course, use plain names with no folders. The file then sits next to your program.
  • Mode "r" needs the file to exist. Modes "w" and "a" make it when it's missing.

Opening a file that isn't there

PYTHONedit me
f = open("secret.txt", "r")
print(f.read())
OUTPUT
FileNotFoundError: [Errno 44] No such file or directory: 'secret.txt'

Every error is a clue! This one names the file Python looked for. The number in the square brackets is an error code. It's 44 in the browser and 2 on most computers. It means the same thing: no such file.

Avoid: a typo in the name

PYTHONedit me
f = open("notes.txt", "w")
f.write("Python is fun")
f.close()

f = open("note.txt", "r")
print(f.read())
OUTPUT
FileNotFoundError: [Errno 44] No such file or directory: 'note.txt'

The program wrote notes.txt but tried to read note.txt. One missing letter, and it's a different file.

Good: one name, stored once

PYTHONedit me
filename = "notes.txt"

f = open(filename, "w")
f.write("Python is fun")
f.close()

f = open(filename, "r")
print(f.read())
f.close()
OUTPUT
Python is fun

Keep the name in a variable, and both open() calls use the very same name. No room for typos.

Common beginner doubt: "Can I stop my program from crashing when the file is missing?" Yes! FileNotFoundError is an exception like the ones in chapter 17, so try and except can catch it. You'll do that in the last topic of this chapter.

Use the exact file name; reading a file that isn't there gives FileNotFoundError.

your turnPredict the output

What will this print?

f = open("scores.txt", "w") f.write("10") f.close() f = open("Scores.txt", "r") print(f.read())
Your turn! What will this code show on the screen?
your turnPredict the output

Remember try and except?

try: age = int("ten") print(age) except ValueError: print("Please type a number")
Your turn! What will this code show on the screen?

Practice: open()

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 170.Python Program to Save a Name in a File and Read It BackEasySolve
  2. 171.Python Program to Copy a Text FileMediumSolve