← Back to Python Course | Chapter 9: File Handling | Lesson 1 of 6

Python File Handling Introduction

File handling is how your program reads and writes files, like opening a notebook to read it or jot something down. You open the file, do your job, and close it.

Introduction to File Streams

File handling is how a program reads data from, or writes data to, files that persist on disk after the program ends -- unlike variables in memory, a saved file's contents survive between separate runs of your script.

Example: Introduction to File Streams

python
with open("notes.txt", "w") as f:
    f.write("saved to disk")  # writes and persists to disk
with open("notes.txt", "r") as f:
    print(f.read())  # reads it back, even in a fresh run

The open() Function

open() is the entry point for all file work -- it takes a file path and a mode string (r for reading, w for writing, and others) and returns a file object you then call methods like .read() or .write() on.

Example: The open() Function

python
f = open("notes.txt", "w")  # "w" mode opens the file for writing
f.write("hello")
f.close()

f = open("notes.txt", "r")  # "r" mode opens the file for reading
print(f.read())
f.close()

Closing Files

Every file you open should eventually be closed with .close() -- this releases the operating system's file handle and, for files opened in write mode, ensures buffered data actually gets flushed to disk rather than lost if the program exits unexpectedly.

Example: Closing Files

python
f = open("notes.txt", "w")
f.write("data")
f.close()  # releases the file handle and flushes buffered data
print(f.closed)

The with Statement

The 'with open(...) as f:' pattern automatically calls .close() for you once the indented block ends, even if an exception is raised inside it -- this makes it the recommended way to work with files instead of manually pairing open() and close() calls.

Example: The with Statement

python
with open("notes.txt", "w") as f:
    f.write("safe write")
print(f.closed)  # automatically closed after the block

File Modes Overview

Beyond basic r (read) and w (write, which erases existing content), a appends new data to a file's end without touching what's already there, and x creates a brand-new file but raises FileExistsError if one already exists at that path -- useful as a safety check against accidental overwrites.

Example: File Modes Overview

python
with open("log.txt", "w") as f:
    f.write("first line\n")  # "w" mode starts the file fresh
with open("log.txt", "a") as f:
    f.write("appended line\n")  # "a" mode adds to the end without erasing
with open("log.txt", "r") as f:
    print(f.read())
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Opening a file and never closing it, which can leave data unwritten or the file locked; use with open(...).
  2. Using the wrong mode, such as "w" when you meant "r", which truncates the file and destroys its contents.
  3. Giving a relative path that does not match the current working directory, which raises FileNotFoundError.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.