Skip to content
5 min read

How to Read and Write Files in Python

A complete beginner's guide to Python file handling. Learn how to open, read, write, and append to files safely using context managers and real-world examples.

#python #beginner #filehandling

Python file handling is a fundamental skill. Whether you’re reading a config file, saving user data, or processing a CSV, you need to know how to work with files. Python makes this clean and safe with built-in tools.

Reading Files

The open() function opens a file. Always use a with statement — it automatically closes the file even if an error occurs:

# Read the entire file as a string
with open("notes.txt", "r") as f:
    content = f.read()
    print(content)

# Read line by line (memory-efficient for large files)
with open("notes.txt", "r") as f:
    for line in f:
        print(line.strip())  # strip() removes the newline character

# Read all lines into a list
with open("notes.txt", "r") as f:
    lines = f.readlines()

The "r" is the mode — “r” for read. If the file doesn’t exist, Python raises FileNotFoundError, so wrap it in a try/except for production code.

Writing and Appending Files

# Write (overwrites existing content)
with open("output.txt", "w") as f:
    f.write("Hello, World!\n")
    f.write("Second line.\n")

# Append (adds to existing content)
with open("output.txt", "a") as f:
    f.write("This line is added at the end.\n")

File Modes Cheat Sheet

ModeMeaning
"r"Read (default)
"w"Write (creates or overwrites)
"a"Append
"rb"Read binary (images, PDFs)
"wb"Write binary

Working with Paths

Hard-coding file paths breaks when you run code on different machines. Use pathlib:

from pathlib import Path

# Build paths that work on Windows, Mac, and Linux
data_dir = Path("data")
file_path = data_dir / "report.txt"

# Check if a file exists before reading
if file_path.exists():
    content = file_path.read_text()

pathlib is the modern way to handle file paths in Python. Prefer it over string concatenation.

Conclusion

Python file handling with open() and context managers is safe, readable, and essential. Always use with open(...) to ensure files are closed properly. For paths, use pathlib instead of string manipulation. These habits will serve you well in every Python project you build.

Read next: Working with JSON in Python

External resource: Python Docs — Reading and Writing Files

Kaikobud Sarkar

Kaikobud Sarkar

Software engineer passionate about backend technologies and continuous learning. I write about Python frameworks, cloud architecture, engineering growth, and staying current in tech.

Related Articles

CSS Flexbox in Plain English: A Beginner's Guide

Learn CSS Flexbox with simple, visual explanations. This guide covers display flex, justify-content, align-items, flex-wrap, and practical layouts every developer needs to know.

#css #flexbox