You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Real programs need to interact with the outside world — reading configuration files, processing data, saving results, and handling errors gracefully. In this lesson, you will learn how to read and write files and how to handle exceptions so your programs do not crash unexpectedly.
open() Function# Basic file reading
file = open("data.txt", "r") # "r" = read mode
content = file.read() # read entire file as a string
print(content)
file.close() # always close the file!
with Statement (Recommended)The with statement automatically closes the file, even if an error occurs:
# Much better — file is closed automatically
with open("data.txt", "r") as file:
content = file.read()
print(content)
# file is automatically closed here
Always use with for file operations.
# read() — read the entire file as one string
with open("data.txt", "r") as f:
content = f.read()
print(content)
# readline() — read one line at a time
with open("data.txt", "r") as f:
first_line = f.readline()
second_line = f.readline()
print(first_line.strip()) # strip() removes the newline character
# readlines() — read all lines into a list
with open("data.txt", "r") as f:
lines = f.readlines()
print(lines) # ['line 1\n', 'line 2\n', 'line 3\n']
# Iterate line by line (most memory-efficient)
with open("data.txt", "r") as f:
for line in f:
print(line.strip())
# "w" — write mode (creates file or OVERWRITES existing content)
with open("output.txt", "w") as f:
f.write("Hello, World!\n")
f.write("This is line 2.\n")
# "a" — append mode (adds to the end of the file)
with open("output.txt", "a") as f:
f.write("This line is appended.\n")
# writelines() — write a list of strings
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("output.txt", "w") as f:
f.writelines(lines)
| Mode | Description |
|---|---|
"r" | Read (default) — file must exist |
"w" | Write — creates or overwrites |
"a" | Append — creates or adds to end |
"x" | Exclusive create — fails if file exists |
"r+" | Read and write |
"b" | Binary mode (e.g., "rb", "wb") |
import csv
# Writing CSV
with open("students.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["Name", "Age", "Grade"]) # header
writer.writerow(["Alice", 20, "A"])
writer.writerow(["Bob", 22, "B"])
writer.writerow(["Charlie", 21, "A"])
# Reading CSV
with open("students.csv", "r") as f:
reader = csv.reader(f)
header = next(reader) # skip header row
for row in reader:
name, age, grade = row
print(f"{name} (age {age}): grade {grade}")
# Using DictReader for named access
with open("students.csv", "r") as f:
reader = csv.DictReader(f)
for row in reader:
print(f"{row['Name']} got {row['Grade']}")
import json
# Writing JSON
data = {
"name": "Alice",
"age": 20,
"courses": ["Maths", "Physics"],
"graduated": False
}
with open("student.json", "w") as f:
json.dump(data, f, indent=2) # indent for pretty printing
# Reading JSON
with open("student.json", "r") as f:
loaded = json.load(f)
print(loaded["name"]) # Alice
print(loaded["courses"]) # ['Maths', 'Physics']
# JSON strings (no file)
json_string = json.dumps(data, indent=2)
print(json_string)
parsed = json.loads(json_string)
print(parsed["age"]) # 20
import os
from pathlib import Path
# Check if a file exists
print(os.path.exists("data.txt")) # True/False
print(Path("data.txt").exists()) # True/False (pathlib)
# Get file size
print(os.path.getsize("data.txt")) # size in bytes
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.