Lesson 14 of 30
File Input and Output
Reading and writing text files, CSV files, and using the with statement.
Writing to a File
Use the built-in open() function with the with statement, which automatically closes the file:
with open("notes.txt", "w") as f:
f.write("Hello from Python!\n")
f.write("Line two\n")
Reading from a File
with open("notes.txt", "r") as f:
content = f.read() # entire file as string
print(content)
with open("notes.txt", "r") as f:
for line in f: # line by line
print(line.strip())
File Modes
| Mode | Meaning |
|---|---|
| r | Read (default) |
| w | Write (overwrites) |
| a | Append |
| x | Create (fails if exists) |
| b | Binary mode (combine: rb, wb) |
Working with CSV Files
import csv
# Write CSV
with open("students.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["Name", "Score"])
writer.writerow(["Alice", 95])
writer.writerow(["Bob", 82])
# Read CSV
with open("students.csv", "r") as f:
reader = csv.DictReader(f)
for row in reader:
print(row["Name"], row["Score"])