Skip to content

Module 13 · File Handling — topic 1 of 15

File handling introduction

Why programs use files, text versus binary files, the open → read/write → close cycle, and how data survives after a program ends.

Beginner 8 min read·Lesson 194 of 306 in Python Programming

Learning objectives

  • Explain why programs need files
  • Describe the open, use, close cycle
  • Distinguish text files from binary files

Definition

File handling is reading data from and writing data to files on disk. Files keep data after a program ends, so they are the simplest way to store settings, records, logs and documents.

Introduction

Variables vanish when a program stops. A to-do list app that forgets every task on exit isn't much use. Files let programs remember.

Why it matters

Almost every real program reads or writes files: configuration, data exports, logs, images and documents. File handling is a core everyday skill.

Detailed explanation

A file is a named sequence of bytes stored on disk. Programs access it through a file object returned by the built-in open().

The basic cycle is: open the file, read or write data, close the file. A with statement closes it automatically.

Text files contain characters (Python str). When reading and writing text, bytes are converted using an encoding — use UTF-8 explicitly with encoding="utf-8".

Binary files (images, audio, PDFs) are handled as bytes, opened with a mode containing b such as "rb" or "wb". No encoding is involved.

Text mode also translates line endings: on Windows, "\n" is written as "\r\n" and converted back when read, so your code always sees "\n".

Relative file names are resolved from the current working directory — the folder the program was started from, which is not always the script's folder.

This module covers opening, reading, writing, appending, modes, closing, with statements, text, CSV and JSON files, paths, directories, pathlib and file errors.

Syntax

Python
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("remember this\n")
with open("notes.txt", encoding="utf-8") as f:
text = f.read()
  • open returns a file object.
  • Text files need an encoding.
  • with closes the file automatically.

Code examples

Write, then read back

Python
with open("hello.txt", "w", encoding="utf-8") as f:
f.write("Hello, file!\n")
with open("hello.txt", encoding="utf-8") as f:
print(f.read().strip())
Output
Hello, file!

A binary file

Python
with open("data.bin", "wb") as f:
f.write(bytes([72, 105, 33]))
with open("data.bin", "rb") as f:
raw = f.read()
print(raw, raw.decode("ascii"), len(raw))
Output
b'Hi!' Hi! 3

More examples

Saving and loading a to-do list

Python
tasks = ["buy milk", "call Ravi", "submit report"]
with open("todo.txt", "w", encoding="utf-8") as f:
for t in tasks:
f.write(t + "\n")
with open("todo.txt", encoding="utf-8") as f:
loaded = [line.rstrip("\n") for line in f]
print(loaded == tasks, len(loaded))
for i, t in enumerate(loaded, 1):
print(f"{i}. {t}")
Output
True 3
1. buy milk
2. call Ravi
3. submit report

Step-by-step explanation

  • Each task is written on its own line by adding "\n".
  • Iterating over the file object yields one line at a time, each ending with "\n".
  • rstrip("\n") removes the line ending so the loaded list equals the original.

Expected output

Running “Saving and loading a to-do list” prints exactly:

TextOutput
True 3
1. buy milk
2. call Ravi
3. submit report

Practical applications

  • Saving game progress or application settings.
  • Exporting reports that other programs or people read.

Best practices

  • Always use with to open files.
  • Specify encoding="utf-8" for text.
  • Use binary mode for non-text data.

Common mistakes

Relying on the default encoding

Avoid

open("notes.txt", "w")

Prefer

open("notes.txt", "w", encoding="utf-8")

The default encoding depends on the operating system; explicit UTF-8 works everywhere.

Important notes

  • Python 3.15 is expected to make UTF-8 the default encoding, but being explicit remains good practice.

Key takeaways

  • Files make data persist.
  • Open → read/write → close; with handles closing.
  • Text files need an encoding; binary files use bytes.

Try it yourself

  1. 1
    Write a program that saves three favourite movies to a file and reads them back.
  2. 2
    Write the bytes of a short message to a binary file and decode them when reading.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

8 questions cover the “File Handling” module. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
  • ModerateWhat is printed?
  • ModerateWhich mode creates a new file but fails if the file already exists?
Practise this module