File Handling in Python

PackagesRead & Write

Files are how programs store and retrieve data permanently – think of saving high scores in a game, reading configuration settings, or processing large datasets.

Python makes file handling simple and safe. The key function is open(), and the recommended way is using the with statement (context manager) which automatically closes the file.

We'll cover everything step by step: opening files in different modes, basic reading and writing, and important best practices.

The open() Function and File Modes

open(filename, mode) returns a file object. Common modes:

  • 'r' – read (default)
  • 'w' – write (creates new or overwrites)
  • 'a' – append (adds to end)
  • 'x' – exclusive creation (fails if exists)
  • 'b' – binary mode
  • 't' – text mode (default)
  • '+' – read and write

Why Use 'with open'?

It automatically closes the file even if an error occurs – preventing resource leaks and file corruption.

Writing to Files

Use write() for single string, writelines() for list of strings.

Reading from Files

read() reads everything, readline() one line, readlines() all lines into list.

Appending to Files

Quick Quiz

We have reviewed and checked the materials, but errors may still occur. The content is provided for educational purposes only, so use it at your own responsibility and verify with other sources if needed.

✨ Ask Lara — your AI study partner

Unlock personalized learning support. Lara can explain lessons, summarize topics, and answer your study questions — available from the Go plan and above.


Lara helps you learn faster — exclusive to ReadyTools Go, Plus, and Max members.

Track Your Progress 🚀

Learn more easily by tracking your progress completely for free.