Reading and Writing Files
Python makes it easy to read from and write to files on your computer. The built-in open() function is used to open a file, and you specify the mode: read ('r'), write ('w'), append ('a'), or read/write ('r+').
The 'with' statement (context manager) is the recommended way to work with files. It automatically closes the file when the block ends, even if an error occurs.
Example
# Writing to a file
with open("example.txt", "w") as f:
f.write("Hello, World!\n")
f.write("This is line 2.\n")
f.write("Python file handling is easy.\n")
# Reading an entire file
with open("example.txt", "r") as f:
content = f.read()
print(content)
# Reading line by line
with open("example.txt", "r") as f:
for line in f:
print(line.strip()) # strip() removes the newline
# Reading all lines into a list
with open("example.txt", "r") as f:
lines = f.readlines()
print(lines) # ['Hello, World!\n', 'This is line 2.\n', ...]
# Appending to a file
with open("example.txt", "a") as f:
f.write("This line was appended.\n") - 'r' — Read mode (default). File must exist.
- 'w' — Write mode. Creates file or overwrites existing content.
- 'a' — Append mode. Adds to the end of the file.
- 'r+' — Read and write mode.
- Always use 'with' to ensure the file is properly closed.
- .read() — Read the entire file as a string
- .readline() — Read one line at a time
- .readlines() — Read all lines into a list
- .write(text) — Write a string to the file
Try File Operations
JavaScript
# Writing a file
with open("example.txt", "w") as f:
f.write("Hello, World!\n")
f.write("Line 2\n")
f.write("Line 3\n")
# Reading the file back
with open("example.txt", "r") as f:
for line in f:
print(line.strip())
print("File operations complete!") Notes
- If you forget to close a file (by not using 'with'), data may not be written completely and system resources may be wasted. Always prefer the 'with' statement.
Working with CSV Files
CSV (Comma-Separated Values) files are a common format for storing tabular data. Python's built-in csv module provides tools for reading and writing CSV files easily.
You can also use the csv.DictReader and csv.DictWriter classes to work with CSV data as dictionaries, which is more readable.
Example
import csv
# Writing CSV
students = [
["Name", "Age", "Grade"],
["Alice", 20, "A"],
["Bob", 22, "B"],
["Charlie", 21, "A"]
]
with open("students.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(students)
# Reading CSV
with open("students.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row)
# ['Name', 'Age', 'Grade']
# ['Alice', '20', 'A']
# ...
# Using DictReader for named columns
with open("students.csv", "r") as f:
reader = csv.DictReader(f)
for row in reader:
print(f"{row['Name']} got grade {row['Grade']}")
# Alice got grade A
# Bob got grade B
# Charlie got grade A Try CSV Files
JavaScript
import csv
# Write CSV
data = [["Name", "Score"], ["Alice", 92], ["Bob", 85]]
with open("scores.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(data)
# Read CSV with DictReader
with open("scores.csv", "r") as f:
reader = csv.DictReader(f)
for row in reader:
print(f"{row['Name']}: {row['Score']}") Notes
- Always pass newline='' when opening CSV files for writing on Windows. Without it, you may get extra blank lines between rows.
