File Handling
Read and write files in Python using built-in functions, context managers, and work with CSV and JSON data formats.
Opening and Reading Files
Python provides the built-in open() function to work with files, supporting various modes such as read, write, and append. The function returns a file object that provides methods like read(), readline(), and readlines() for accessing file contents. It is important to close files after use to free system resources. Files can be opened in text mode (default) or binary mode for non-text data.
# Reading an entire file
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
# Reading line by line
file = open("example.txt", "r")
for line in file:
print(line.strip())
file.close()
# Reading into a list of lines
file = open("example.txt", "r")
lines = file.readlines()
print(f"File has {len(lines)} lines")
file.close()
# Reading specific number of characters
file = open("example.txt", "r")
first_100 = file.read(100)
print(first_100)
file.close()
Writing Files and the with Statement
The with statement provides a clean way to handle file operations by automatically closing the file when the block exits, even if an exception occurs. Writing to a file uses the write() or writelines() methods, with the 'w' mode creating or overwriting the file and the 'a' mode appending to it. The with statement is the recommended approach for file handling in Python as it ensures proper resource management. You can also open multiple files simultaneously using nested or combined with statements.
# Writing with context manager
with open("output.txt", "w") as f:
f.write("First line\n")
f.write("Second line\n")
f.write("Third line\n")
# Appending to a file
with open("output.txt", "a") as f:
f.write("Appended line\n")
# Writing multiple lines at once
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("output.txt", "w") as f:
f.writelines(lines)
# Reading and writing simultaneously
with open("input.txt", "r") as src, open("output.txt", "w") as dst:
for line in src:
dst.write(line.upper())
Working with CSV Files
The csv module in Python's standard library provides reader and writer objects for handling comma-separated value files. The DictReader and DictWriter classes allow you to work with CSV data as dictionaries, using column headers as keys. CSV files are one of the most common data exchange formats, especially for tabular data from spreadsheets and databases. Proper handling of delimiters, quoting, and encoding ensures your CSV processing is robust.
import csv
# Writing CSV data
with open("students.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["Name", "Age", "Grade"])
writer.writerow(["Alice", 22, "A"])
writer.writerow(["Bob", 23, "B+"])
writer.writerow(["Charlie", 21, "A-"])
# Reading CSV data
with open("students.csv", "r") as f:
reader = csv.reader(f)
header = next(reader)
for row in reader:
print(f"{row[0]} is {row[1]} years old with grade {row[2]}")
# Using DictReader and DictWriter
with open("students.csv", "r") as f:
reader = csv.DictReader(f)
for row in reader:
print(f"{row['Name']}: {row['Grade']}")
Working with JSON
The json module provides functions for serializing Python objects to JSON strings and deserializing JSON strings back to Python objects. The json.dumps() function converts a Python object to a JSON string, while json.loads() parses a JSON string into a Python object. For file operations, json.dump() and json.load() work directly with file objects. JSON is the standard data format for web APIs and configuration files in modern applications.
import json
# Python object to JSON string
data = {
"name": "Alice",
"age": 30,
"hobbies": ["reading", "coding", "hiking"],
"address": {
"city": "New York",
"state": "NY"
}
}
json_string = json.dumps(data, indent=2)
print(json_string)
# JSON string to Python object
parsed = json.loads(json_string)
print(parsed["hobbies"][1]) # "coding"
# Writing JSON to a file
with open("data.json", "w") as f:
json.dump(data, f, indent=2)
# Reading JSON from a file
with open("data.json", "r") as f:
loaded = json.load(f)
print(loaded["name"]) # "Alice"