Python File Handling

Ka Kavitha V Updated 03 Oct 2026
6 min read

File Handling

Variables live in memory, which means their data disappears as soon as a program ends. To keep data — user settings, logs, reports, uploaded content, or saved game progress — a program must write it to a file on disk and read it back later.

File handling is how a program creates, reads, updates, and deletes files. Python provides built-in tools for all of these tasks, without needing any extra libraries.

This lesson introduces the core tool, the open() function, and the file modes that control what you can do with a file. The following lessons cover reading, writing, and deleting files in detail.

The open() Function

The primary function for working with files is open(). It connects your program to a file and returns a file object — an object with methods such as read(), write(), and close().

Syntax

file_object = open(filename, mode)
ParameterDescription
filenameThe name of the file, or its path (for example, "notes.txt" or "data/notes.txt")
modeA short string that specifies how the file is opened: for reading, writing, appending, and so on

The Typical File Workflow

Working with a file always follows three steps:

  1. Open the file with open().
  2. Work with it — read or write data.
  3. Close it with close(), to release it back to the operating system.

File Open Modes

Text Modes

ModeNameBehaviorIf the File Does Not ExistIf the File Exists
"r"ReadOpens the file for reading (default)Raises FileNotFoundErrorReads from the beginning
"a"AppendAdds new content to the end of the fileCreates the fileKeeps existing content
"w"WriteWrites content from the beginningCreates the fileErases all existing content
"x"Exclusive createCreates a new file for writingCreates the fileRaises FileExistsError

Choosing a mode:

  • Use "r" to read a file.
  • Use "a" to add to a log or history without losing earlier entries.
  • Use "w" to replace a file completely — but be careful, because existing content is lost immediately.
  • Use "x" when you must never overwrite an existing file.

Warning: Opening a file in "w" mode erases its content as soon as the file is opened — even before you write anything.

Text vs Binary Mode

A second letter specifies how the data is handled:

ModeNameData TypeUsed For
"t"Text (default)Strings (str).txt, .csv, .json, .html, .py files
"b"BinaryBytes (bytes)Images, audio, video, PDFs, ZIP files

The two letters are combined:

CombinationMeaning
"rt" or "r"Read text
"rb"Read binary
"wt" or "w"Write text
"wb"Write binary
"ab"Append binary

A + can be added to open a file for both reading and writing — for example, "r+" — but this is less common and easier to misuse.

Opening a File for Reading

To open a file for reading, you only need the filename:

data = open("notes.txt")

This works because both "r" (read) and "t" (text) are the default values. The line above is equivalent to:

data = open("notes.txt", "rt")

Example: Reading File Content

Assume a file named notes.txt exists in the same folder as your Python script and contains:

Buy groceries
Call the bank
file = open("notes.txt", "r")
content = file.read()
print(content)
file.close()

Expected output:

Buy groceries
Call the bank

What happens:

  1. open("notes.txt", "r") opens the file and returns a file object.
  2. file.read() reads the entire content as a single string.
  3. print(content) displays it.
  4. file.close() closes the file.

Why Closing Files Matters

Always close a file when you are finished with it:

  • It frees system resources — the operating system limits how many files a program can have open.
  • It ensures written data is actually saved. Python may hold written data in a temporary buffer and write it to disk only when the file is closed.
  • On some systems, an open file cannot be moved, renamed, or deleted by other programs.

Remembering to call close() is easy to forget — and if an error occurs before close() runs, the file stays open. The with statement solves both problems by closing the file automatically.

with open("notes.txt", "r") as file:
    print(file.read())

Expected output:

Buy groceries
Call the bank

How it works:

  • open(...) opens the file, and as file names the file object.
  • The indented block uses the file.
  • As soon as the block ends — normally or because of an error — Python closes the file.
with open("notes.txt", "r") as file:
    content = file.read()

print(file.closed)

Expected output:

True

The with statement is cleaner, safer, and the standard approach in professional Python code. The rest of the file handling lessons use it.

File Paths

A filename alone, such as "notes.txt", refers to a file in the current working directory — usually the folder from which you ran the script. To reach a file elsewhere, use a path:

Path TypeExampleMeaning
Relative"data/notes.txt"Relative to the current working directory
Absolute (Windows)"C:/Users/Asha/notes.txt"The full location on the drive
Absolute (Linux/macOS)"/home/asha/notes.txt"The full location from the root

Tip: Forward slashes (/) work on Windows too. If you use backslashes, write a raw string — r"C:\Users\Asha\notes.txt" — so that sequences like \n are not treated as escape characters.

Handling a Missing File

Reading a file that does not exist raises an error:

with open("missing.txt", "r") as file:
    print(file.read())

Output:

FileNotFoundError: [Errno 2] No such file or directory: 'missing.txt'

Handle it with try and except:

try:
    with open("missing.txt", "r") as file:
        print(file.read())
except FileNotFoundError:
    print("The file could not be found.")

Expected output:

The file could not be found.

Specifying the Encoding

Text files are stored as bytes using an encoding that maps characters to bytes. The default encoding can differ between operating systems, which may cause errors or garbled text with non-English characters. Specifying UTF-8 makes your code behave the same everywhere:

with open("notes.txt", "r", encoding="utf-8") as file:
    print(file.read())

Using encoding="utf-8" for text files is a good habit.

Common Mistakes

MistakeProblem
Forgetting to close the fileResources are not released; written data may be lost
Using "w" when you meant "a"Existing content is erased
Reading a file that does not existFileNotFoundError
Running the script from a different folderRelative paths point somewhere unexpected
Using backslashes in normal strings"C:\new" contains a newline character; use / or a raw string
Opening an image in text modeDecoding errors; use "rb" for binary files
  • Python Opening Files — reading entire files, parts of files, and lines
  • Python Writing and Creating Files — writing, appending, and creating files
  • Python Deleting Files — removing files and folders with the os module
  • Python Exception Handling — handling FileNotFoundError and other errors

0 Comments

Reviewed before they appear

No comments yet.

Python
Ask about this post
AI Ask about this post

Ask questions about Python File Handling and get answers drawn from it.

Signed-in readers only.