Skip to content
Python Programming

File Handling in Python

Beginner Lesson 8 of 10

Learn to work with files in Python - reading, writing, and managing file operations.

# Using context manager (recommended)
with open("file.txt", "r") as f:
content = f.read()
# File modes
# 'r' - read (default)
# 'w' - write (overwrites)
# 'a' - append
# 'x' - create (fails if exists)
# 'b' - binary mode
# Read entire file
with open("file.txt", "r") as f:
content = f.read()
# Read line by line
with open("file.txt", "r") as f:
for line in f:
print(line.strip())
# Read all lines as list
with open("file.txt", "r") as f:
lines = f.readlines()
with open("output.txt", "w") as f:
f.write("Hello, World!\n")
f.writelines(["Line 1\n", "Line 2\n"])
import json
# Write JSON
data = {"name": "Alice", "age": 25}
with open("data.json", "w") as f:
json.dump(data, f, indent=2)
# Read JSON
with open("data.json", "r") as f:
data = json.load(f)

Continue to Exception Handling →