Why Files Matter

Understand why programs need to read and write files

Programs and data

When a program runs, its variables live in memory. When the program stops, that data disappears. Files let you store data permanently — on disk — so it survives between runs.

What you can do with files

  • Read existing data into your program
  • Write results your program produces
  • Append new entries to an existing file

Common file formats

FormatExtensionUse case
Plain text.txtLogs, notes, raw data
CSV.csvTables, spreadsheets
JSON.jsonConfig files, API responses

How Python opens files

Python uses the built-in open() function to open a file. You always specify two things:

  • The filename — the path to the file
  • The mode — what you want to do with it

ModeMeaning
"r"Read (default)
"w"Write (overwrites existing content)
"a"Append (adds to the end)

The with statement

Python's with statement opens a file and automatically closes it when the block ends. This is the standard way to work with files.

with open("data.txt", "r") as file:
    content = file.read()
# File is closed automatically here

Always use with to open files. It prevents data loss from files left open accidentally.

Next Chapter →