Python for Absolute Beginners

Lesson 4 of 6

Working with Files

Programs are more useful when they can save data between runs. Python's built-in open() reads and writes files.

Pythonshares state with other Python blocks

The with statement

with open(...) as f: opens the file and guarantees it gets closed automatically when the block ends, even if an error happens inside it. Without with, you'd have to remember to call f.close() yourself.

Common modes

ModeMeaning
"r"Read (default), errors if the file doesn't exist
"w"Write, creates the file or overwrites it completely
"a"Append, adds to the end without erasing existing content

📝 Files Quiz

Passing score: 70%
  1. 1.Which file mode adds new content to the end of a file without erasing what is already there?

  2. 2.The `with` statement automatically closes a file when its block ends.

  3. 3.Opening a file for writing, overwriting any existing content, uses mode ____.