Python Basics — File Handling

1 minute read

File Handling

Reading and writing files is one of the most practical skills in programming. Python makes it straightforward with built-in functions and powerful libraries for CSV, JSON, and more.

What You’ll Learn

# Topic What You’ll Master
1 Reading Files open(), read modes, iterating lines
2 Writing Files Write mode, append mode, creating files
3 Context Managers The with statement — the proper way
4 CSV Files Reading & writing spreadsheet data
5 JSON Files Working with API data and config files
6 Practice Exercises Test your understanding

Quick Preview

# Write a file
with open("notes.txt", "w") as f:
    f.write("Hello, File!\n")
    f.write("Python makes this easy.\n")

# Read a file
with open("notes.txt", "r") as f:
    content = f.read()
    print(content)
# Hello, File!
# Python makes this easy.

# Work with JSON
import json

data = {"name": "Alice", "scores": [85, 92, 78]}
with open("data.json", "w") as f:
    json.dump(data, f, indent=2)

File Modes at a Glance

Mode Description File Exists File Doesn’t Exist
"r" Read (default) Opens for reading FileNotFoundError
"w" Write Overwrites content Creates new file
"a" Append Adds to end Creates new file
"x" Exclusive create FileExistsError Creates new file
"rb" Read binary Opens bytes FileNotFoundError
"wb" Write binary Overwrites bytes Creates new file

Start Learning: Reading Files →

Updated: