Python allows you to read from and write to files easily. This tutorial covers text, CSV, and JSON files, as well as how to use context managers (with
statements) for managing file resources efficiently.
File Handling in Python
1. Reading and Writing Text Files
Text files are simple to read and write in Python. Here's how to open, read, and write text files:
Reading a Text File
with open("example.txt", "r") as file:
content = file.read()
print(content)
Explanation: The with
statement opens the file and automatically closes it after the block. "r"
is the mode for reading.
Writing to a Text File
with open("example.txt", "w") as file:
file.write("Hello, world!")
Explanation: "w"
mode opens the file for writing. If the file exists, it will overwrite the content; otherwise, it creates a new file.
Text Files Quiz
What happens if you open a non-existent file in "r" mode?
How do you append to a file without overwriting existing content?
2. Working with CSV Files
CSV files are commonly used for data storage. Python's csv
module helps with reading and writing CSV files.
Reading a CSV File
import csv
with open("data.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
Explanation: csv.reader
reads each row as a list of values, making it easy to process CSV data.
Writing to a CSV File
import csv
data = [["Name", "Age"], ["Alice", 30], ["Bob", 25]]
with open("data.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(data)
Explanation: csv.writer
writes data as rows in the CSV file. newline=""
ensures no extra blank rows.
CSV Files Quiz
Why is newline=""
important when writing CSV files?
How would you read a CSV file with headers into a dictionary?
3. Working with JSON Files
JSON files are popular for storing structured data. Python's json
module makes it easy to read and write JSON files.
Reading a JSON File
import json
with open("data.json", "r") as file:
data = json.load(file)
print(data)
Explanation: json.load
reads and parses JSON data, converting it into Python dictionaries and lists.
Writing to a JSON File
import json
data = {"name": "Alice", "age": 30}
with open("data.json", "w") as file:
json.dump(data, file, indent=4)
Explanation: json.dump
writes Python data to a JSON file. The indent
parameter formats the JSON for readability.
JSON Files Quiz
What Python data type does JSON most closely resemble?
What does the indent
parameter do in json.dump()
?
4. Using Context Managers
Using with
statements (context managers) ensures that files are closed automatically after processing, even if errors occur. This practice is safer and more efficient.
Example
with open("example.txt", "r") as file:
data = file.read()
# File is automatically closed after this block
Note: This approach prevents memory leaks and avoids having to manually close files.
Context Managers Quiz
What's the main advantage of using with
for file handling?
What happens if an exception occurs inside a with
block?