🎓 A1Learner
🔍

Python Open & Close Files

A file holds text on disk under a name. open() gives a file object for reading or writing that file.

Open a file by hand

open() takes a name and a mode. The t in the mode means text mode.

f = open("notes.txt", "wt")
print("opened")
f.close()

Three modes at work

The w mode writes. The a mode adds. The r mode reads.

with open("notes.txt", "w") as f:
    f.write("one")
with open("notes.txt", "a") as f:
    f.write(" two")
with open("notes.txt", "r") as f:
    print(f.read())

Close by hand

Call close() when you finish. An open file holds its place on disk.

f = open("notes.txt", "w")
f.write("done")
f.close()
print("closed")

Create with x

The x mode makes a brand new file. Run this once in a fresh folder.

with open("fresh.txt", "x") as f:
    f.write("new file")
print("created")

Let with close it

The with form is the keeper. It closes the file at the end of the block.

with open("notes.txt", "w") as f:
    f.write("safe")
print("closed for you")

Example

f = open("notes.txt", "w")
f.write("First note\n")
f.close()

f = open("notes.txt", "a")
f.write("Second note\n")
f.close()

with open("notes.txt", "a") as f:
    f.write("Third note\n")

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

Key points

  • File object: the value open() gives back.
  • You use it to read or write.
  • Mode: a short text code that says what you may do with the file
  • Use "r" to open a file for reading
  • Use "w" to open a file for writing.
  • Old content is replaced.
  • Use "a" to open a file for adding at the end
  • Use "x" to create a new file.
  • It fails if the file already exists.
  • Use "t" for text mode.
  • Text mode is the default mode.
  • Use with to open a file.
  • The with block closes the file for you.

In this example, the first open uses mode w and closes by hand. It writes the first note line. The second open uses mode a and also closes by hand. It adds the second note line. The third open uses the with form. It adds the third line, and with closes the file. The last block reads the file and prints all three lines.

Note

A file left open can lose its last writes.

The with form removes that risk.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Which way closes the file for you at the end of a block?