Python File I/O
Learn to read from and write to files, use the with statement for safe file handling, and process CSV data.
Reading and Writing Files
Python can read from and write to files on your computer. The open() function creates a file object. The most common modes are "r" (read), "w" (write), and "a" (append).
# Writing to a file
with open("greeting.txt", "w") as file:
file.write("Hello, World!\n")
file.write("Welcome to Python file I/O.\n")
file.write("This is line 3.\n")
# Reading the entire file
with open("greeting.txt", "r") as file:
content = file.read()
print(content)
# Reading line by line
with open("greeting.txt", "r") as file:
for line in file:
print(line.strip()) # strip() removes the \n
The with Statement
The with statement is the recommended way to work with files. It automatically closes the file when the block ends, even if an error occurs. This prevents data loss and resource leaks.
# WITHOUT with (not recommended)
file = open("data.txt", "r")
content = file.read()
file.close() # You must remember to close!
# WITH with (recommended - auto-closes)
with open("data.txt", "r") as file:
content = file.read()
# File is automatically closed here
# Appending to a file
with open("log.txt", "a") as file:
file.write("New log entry added.\n")
with when working with files. It ensures the file is properly closed.
Processing CSV Files
CSV (Comma-Separated Values) files are a common way to store tabular data. Python's built-in csv module makes reading and writing CSV files simple.
import csv
# Writing a CSV file
with open("students.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age", "Score"]) # Header
writer.writerow(["Alice", 16, 92])
writer.writerow(["Bob", 17, 85])
writer.writerow(["Charlie", 16, 78])
# Reading a CSV file
with open("students.csv", "r") as file:
reader = csv.reader(file)
header = next(reader) # Skip header row
print(f"Columns: {header}")
for row in reader:
name, age, score = row
print(f"{name} (age {age}): {score}%")
Key Vocabulary
File I/O
Input/Output operations for reading data from and writing data to files on disk.
File Mode
How the file is opened: "r" read, "w" write, "a" append.
CSV
Comma-Separated Values: a text format for storing tabular data where each field is separated by a comma.
Context Manager
The with statement that automatically handles resource cleanup (e.g., closing files).
Worked Examples
Save and load a to-do list
# Save tasks to a file
tasks = ["Buy groceries", "Finish homework", "Clean room"]
with open("todo.txt", "w") as file:
for task in tasks:
file.write(task + "\n")
print("Tasks saved!")
# Load tasks from the file
with open("todo.txt", "r") as file:
loaded_tasks = [line.strip() for line in file]
print(f"Loaded {len(loaded_tasks)} tasks:")
for i, task in enumerate(loaded_tasks, 1):
print(f" {i}. {task}")
Step 1: Write each task on a new line with \n.
Step 2: Read the file back and use .strip() to remove newline characters.
Count words in a text file
# First create a sample file
with open("sample.txt", "w") as file:
file.write("Python is a great language.\n")
file.write("It is easy to learn.\n")
file.write("Python is used everywhere.\n")
# Count words, lines, and characters
with open("sample.txt", "r") as file:
content = file.read()
lines = content.strip().split("\n")
words = content.split()
chars = len(content)
print(f"Lines: {len(lines)}")
print(f"Words: {len(words)}")
print(f"Characters: {chars}")
Step 1: Read the entire content, then split by newlines for lines and by spaces for words.
Output: Lines: 3 | Words: 15 | Characters: 78
Read a CSV and calculate averages
import csv
# Read scores and calculate average per student
with open("students.csv", "r") as file:
reader = csv.reader(file)
next(reader) # Skip header
for row in reader:
name = row[0]
score = int(row[2])
if score >= 50:
status = "PASS"
else:
status = "FAIL"
print(f"{name}: {score}% - {status}")
Step 1: Use csv.reader() and skip the header with next().
Step 2: Convert score to integer and determine pass/fail status.
Knowledge Check
Select the correct answer for each question. Click "Check Answer" to see if you are right.
Question 1
Which mode opens a file for reading only?
Question 2
What is the main advantage of using the with statement for files?
Question 3
What does the "a" mode do when opening a file?
Question 4
What does CSV stand for?
Question 5
What method reads the entire file content as a single string?
Key Concepts Summary
-
●
Use
open(filename, mode)to open files: "r" read, "w" write, "a" append. -
●
Always use the
withstatement for automatic file closing. -
●
.read()gets the whole file;.readline()gets one line;.readlines()gets a list of lines. -
●
The
csvmodule handles reading and writing CSV files withcsv.reader()andcsv.writer(). - ● "w" mode erases existing content. Use "a" to add to existing files.