Lesson 94 +10 XP

File Handling

File Handling

Python reads and writes files with built-in functions. The key function is open().

Open a file

f = open("demofile.txt")

Modes for open()

The second argument selects a mode:

ModeMeaning
"r"Read (default)
"a"Append (add to the end)
"w"Write (overwrite or create)
"x"Create (error if it exists)
"t"Text mode (default)
"b"Binary mode

Combine them, like "rb" for read binary.

The "x" create mode

f = open("newfile.txt", "x")  # errors if the file exists

The "a" append mode

f = open("demofile.txt", "a")
f.write("Now the file has more content!")

Adds to the end without deleting what's there.

The "w" write mode

f = open("demofile.txt", "w")
f.write("Whoops! I deleted the content!")

Overwrites everything, or creates the file if it's missing.

Always close files

f.close()

The with statement (recommended)

with closes the file for you automatically:

with open("demofile.txt") as f:
    content = f.read()

TL;DR

  • open(filename, mode) opens a file.
  • Modes: r read, a append, w write, x create.
  • Add t for text (default) or b for binary.
  • Always close files; with does it automatically.