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
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 →