Python File Handling: Read, Write, and Append Examples

Python File Handling: Read, Write, and Append Examples


If you are just starting out with Python and want to save data to files, read texts, or keep logs, this beginner-friendly guide is for you. In this Python file handling tutorial for beginners, we will walk through Python file handling read write and append examples using simple, practical snippets. You will learn how to read a file in Python, how to write to a file in Python, how to append to a file in Python, and when to use the Python open file modes r w a (and more). By the end, you’ll be comfortable opening and closing files safely, handling common errors, and practicing with small exercises. For more Python basics, see our Python tutorials at CodDesire.

Key takeaways: Python file handling — read, write, append

  • Use with open(…) for safe, automatic closing — fewer bugs and no leaked file handles.
  • Read (r): open existing text safely without changing it; pair with read(), readline(), or iteration.
  • Write (w): create or overwrite from the start; to avoid accidental loss, consider x (exclusive create) first.
  • Append (a): add to the end for logs/journals; a+ lets you read and append in one handle.
  • Prefer encoding=”utf-8″ for text; for CSV, open with newline=”” and use the csv module.
  • Paths: use pathlib.Path for clean folder creation (mkdir) and text helpers (read_text/write_text).

Why file handling matters

Python file handling read write and append examples: script to file flow for beginners
Read, write, and append at a glance—how a Python script interacts with files.

Programs don’t always run inside an IDE forever. You often need to keep results, store logs, or load configuration. File handling lets your Python programs:

  • Remember information between runs (saving data to disk)
  • Import text or numbers from existing files
  • Write logs for debugging and auditing
  • Work with assets such as CSVs, images, and binary files

open() and file modes: r, w, a, x, +, b

Python file handling read write and append examples: modes and file pointer behavior
How read, write, and append change the file pointer and content.

The built-in open() function is the entry point for reading and writing files. Its most important argument is the mode, which decides what you want to do: read, write, append, or create exclusively. Here is a quick comparison of common modes.

Mode Meaning Creates file? Truncates existing? Pointer position Typical use
r Read text No No Start Open an existing file to read
w Write text Yes Yes Start Create/overwrite a file
a Append text Yes No End Add content to the end
x Exclusive create Yes Start Create a new file; fail if it exists
r+ Read/write No No Start Modify without truncating
w+ Read/write Yes Yes Start Reset file and then read/write
a+ Append/read Yes No End (for writes) Read and append to end
rb / wb / ab Binary modes Varies Varies Varies Images, PDFs, any non-text data

Quick mode picker flow

Need to only read an existing text file?
Use r (add brb for binary).
Want to overwrite (or create) with fresh content?
Use w (add +w+ if you must read too).
Want to add to the end without deleting anything?
Use a (add +a+ to read and append).
Need to ensure a brand‑new file only?
Use x (fails if the file already exists).
Need to edit without truncating?
Use r+ (read, then write in place).
Working with non‑text (images, PDFs, bytes)?
Add b to your chosen mode: rb, wb, ab, r+b, etc.

Tip: Combine flags: a+ means “append and read”; rb means “read binary”. Always use with open(...) to auto‑close.

Safe opening and auto-closing with with

Always prefer a context manager. Using with open(...) closes the file automatically, even if errors happen.

# Syntax pattern
with open("filename.txt", mode="r", encoding="utf-8") as f:
data = f.read() # work with the file
# file is now closed automatically

Tip: The default text encoding depends on your OS and settings. For predictable behavior, pass encoding="utf-8".

How to read a file in Python (r)

Read the entire file at once

Code
# Read the whole file into a string
with open("poem.txt", "r", encoding="utf-8") as f:
    text = f.read()
print(text)

Read line by line efficiently

# Iterate over lines without loading all content at once
with open("poem.txt", "r", encoding="utf-8") as f:
for i, line in enumerate(f, start=1):
print(f"{i}: {line.rstrip()}")

Read the first N characters or one line

with open("poem.txt", "r", encoding="utf-8") as f:
first_20 = f.read(20) # first 20 characters
f.seek(0) # go back to start
first_line = f.readline() # read one line
print(first_20)
print(first_line)

Reading text with pathlib (clean and concise)

from pathlib import Path

p = Path("notes.txt")
content = p.read_text(encoding="utf-8")
print(content)

How to write to a file in Python (w)

Use write mode to create or overwrite files. Be careful: w erases existing content.

Code
# Write text to a new (or overwritten) file
with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("First linen")
    f.writelines(["Second linen", "Third linen"])

print("Wrote 3 lines to notes.txt")

Create missing folders before writing

open() will not create parent folders. Make them first:

from pathlib import Path

p = Path("output/reports/summary.txt")
p.parent.mkdir(parents=True, exist_ok=True)

with open(p, "w", encoding="utf-8") as f:
f.write("Report summaryn")

Writing CSV properly (newline control)

When writing CSVs, pass newline="" so the csv module handles newlines correctly.

import csv

rows = [
["id", "name"],
[1, "Asha"],
[2, "Dev"]
]

with open("students.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerows(rows)

How to append to a file in Python (a)

Append mode adds new content to the end without deleting the existing data. This is great for logs and running records.

from datetime import datetime

with open("app.log", "a", encoding="utf-8") as f:
f.write(f"{datetime.now().isoformat()} - Application startedn")

Append and then read what you wrote (a+)

# a+ lets you append and read in the same handle
with open("events.log", "a+", encoding="utf-8") as f:
f.write("New event recordedn")
f.seek(0) # move to start before reading
for line in f:
print(line.rstrip())

Combined modes and binary files

Read and then write without truncation (r+)

# Insert a header at the very start of the file
with open("todo.txt", "r+", encoding="utf-8") as f:
old = f.read()
f.seek(0)
f.write("=== TODO LIST ===n" + old)

Copy a binary file (images, PDFs) safely

# Copy binary data in chunks
src = "photo.jpg"
dst = "photo_copy.jpg"

with open(src, "rb") as fin, open(dst, "wb") as fout:
for chunk in iter(lambda: fin.read(8192), b""):
fout.write(chunk)

print("Copied photo.jpg to photo_copy.jpg")

Relative risk of data loss by mode (qualitative)

Longer bar = higher chance of overwriting or losing existing content if misused
r

very low

a

low

a+

low

x

low

r+

medium

w

very high

w+

very high

This is a qualitative learning aid. Back up important files and prefer x or temp files when safety matters.

Safety tips: create files without overwriting and handle errors

Exclusive create with x

Code
# Create a new file but fail if it already exists
try:
    with open("unique.txt", "x", encoding="utf-8") as f:
        f.write("Created once onlyn")
except FileExistsError:
    print("unique.txt already exists — not overwriting.")

Helpful error handling

try:
with open("missing.txt", "r", encoding="utf-8") as f:
print(f.read())
except FileNotFoundError:
print("File not found — check the path and filename.")
except PermissionError:
print("No permission — try a different folder or run with proper rights.")

Encodings and newlines: best practices that prevent bugs

  • Always specify encoding="utf-8" for predictable text behavior across systems.
  • Reading text: Python handles different newline styles automatically by default.
  • Controlling newlines: for CSV or when you must preserve exact line endings, pass newline="" to open() and let the library (like csv) manage them.
  • Decoding errors: if you see UnicodeDecodeError, the file’s encoding may not be UTF-8. Try a matching encoding (e.g., latin-1) or confirm the source encoding.
# Example: try a different encoding if decoding fails with UTF-8
try:
with open("legacy.txt", "r", encoding="utf-8") as f:
data = f.read()
except UnicodeDecodeError:
with open("legacy.txt", "r", encoding="latin-1") as f:
data = f.read()
print(len(data))

Step by step guide to Python file handling (beginner friendly)

  1. Create a practice folder and a new file by writing.
  2. Read the file back to verify content.
  3. Append new lines and confirm they appear at the end.
from pathlib import Path
from datetime import datetime

# 1) Create folder and write
base = Path("practice")
base.mkdir(exist_ok=True)
target = base / "journal.txt"

with open(target, "w", encoding="utf-8") as f:
f.write("Day 1: Started learning files.n")

# 2) Read back
print("After write:")
with open(target, "r", encoding="utf-8") as f:
print(f.read())

# 3) Append entries
with open(target, "a", encoding="utf-8") as f:
f.write(f"Day 2: Continued at {datetime.now().isoformat()}n")

print("After append:")
with open(target, "r", encoding="utf-8") as f:
print(f.read())

Common errors in Python file handling and fixes

  • FileNotFoundError: The path is wrong or the file does not exist. Fix: check spelling, use Path to build paths, or create the file first.
  • PermissionError: Writing to a protected folder. Fix: choose a writable directory (e.g., your user folder) or adjust permissions.
  • UnicodeDecodeError: Encoding mismatch when reading. Fix: specify the correct encoding (utf-8, latin-1, etc.).
  • Accidental overwrite: Using w on an important file. Fix: use x for exclusive creation, or back up first.

Practice exercises for Python file handling

  1. Create a program that writes five lines of your favorite quotes to quotes.txt, then reads and prints them with line numbers.
  2. Write a script that appends a timestamped message to run.log each time it runs. Verify by reading the file after appending.
  3. Copy a binary file (e.g., an image) to a new file using chunked reads in rb/wb modes.
  4. Use csv to write a small table (3 rows) to scores.csv, then open it and print the contents line by line.
  5. Try to create a file with x twice, catch FileExistsError, and print a friendly message.

FAQ: Python file handling read, write, append examples

What is the difference between read, write, and append in Python file handling?

Read (r) opens an existing file to get its contents. Write (w) creates a new file or clears an existing one before writing. Append (a) adds new data to the end without removing existing content.

How do I open and close a file safely in Python?

Use a context manager: with open(...). It closes the file automatically after the block, even if an error occurs.

What do file modes r, w, a, and r+ mean in Python?

  • r: read text (file must exist)
  • w: write text (create or truncate)
  • a: append text (create if missing, no truncate)
  • r+: read and write without truncating (file must exist)

How can I read a text file line by line in Python?

with open("data.txt", "r", encoding="utf-8") as f:
for line in f:
print(line.rstrip())

Why am I getting FileNotFoundError and how do I fix it in Python?

The path or filename is incorrect, or the file doesn’t exist yet. Fix by checking the working directory, correcting the path, creating the file first (e.g., with w or x), or using Path(...).parent.mkdir(parents=True, exist_ok=True) to create missing folders before writing.

Beginner friendly Python read, write, append tutorial recap

  • Use with open(...) for automatic closing.
  • Pick the right mode: r to read, w to overwrite, a to append, x to create safely.
  • Specify encoding="utf-8" for text files.
  • For CSVs, open with newline="" and use the csv module.
  • Use pathlib.Path for clean path handling and read_text/write_text.
  • Handle exceptions like FileNotFoundError and PermissionError to make your scripts robust.

Sources / Further reading

Keep practicing these Python file open and close with examples, and revisit this page whenever you need a quick refresher on Python file handling read write and append examples. For more lessons, explore our Python section at CodDesire.

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted