We're making some improvements. Some features may be temporarily unavailable.
intermediate20 min

Working with Files

Reading from and writing to files in Python

Why Work with Files?

Reading and writing files lets your programs store data permanently — not just in memory while the program runs.

Note: In the browser (Pyodide), file operations work with a virtual filesystem. The concepts are the same as on a real computer!

Writing to a File

Writing Files

Output
Run your code to see output here

File Modes

  • "r" — Read (default)
  • "w" — Write (overwrites existing file)
  • "a" — Append (add to end)
  • "r+" — Read and write

Reading Files

Reading Files

Output
Run your code to see output here

The with Statement

The with statement automatically closes the file when you're done — even if an error occurs. Always use with when working with files.

Appending to Files

Output
Run your code to see output here

Check Your Understanding

What file mode should you use to add content to an existing file without erasing it?

Check Your Understanding

Why is `with open(...) as f:` preferred over `f = open(...)`?

Exercise

Write a program that creates a file called `shopping.txt`, writes 3 items to it (one per line), then reads and prints the file contents.

Python will load on first run

Questions & Discussion

Sign in to ask a question or join the discussion.

Loading comments...