Lesson 14: Python File Handling and CSV/JSON | Coding Class Series
Lesson 14: Python File Handling and CSV/JSON | Coding Class Series
Introduction
Welcome to Lesson 14!
In this lesson, we will learn how to work with files in Python, including reading, writing, and updating text files, as well as working with CSV and JSON formats.
File handling is essential for storing data permanently and exchanging it between programs.
1. Opening and Closing Files
Use the open() function to open a file. Always close it after use.
# Open a file in write mode
file = open("example.txt", "w")
file.write("Hello, Python!")
file.close()
# Open the file in read mode
file = open("example.txt", "r")
print(file.read()) # Hello, Python!
file.close()
2. Using with Statement
with automatically closes the file after usage.
with open("example.txt", "w") as f:
f.write("Using with statement!")
with open("example.txt", "r") as f:
print(f.read()) # Using with statement!
3. Reading Files
read(): reads the entire filereadline(): reads one line at a timereadlines(): reads all lines into a list
with open("example.txt", "r") as f:
print(f.readline())
print(f.readlines())
4. Writing and Appending Files
"w"mode: write (overwrites existing content)"a"mode: append (adds new content)
with open("example.txt", "a") as f:
f.write("\nAppending a new line!")
with open("example.txt", "r") as f:
print(f.read())
5. Working with CSV Files
CSV (Comma Separated Values) files store tabular data.
import csv
# Writing to a CSV file
with open("students.csv", "w", newline="") as csvfile:
writer = csv.writer(csvfile)
writer.writerow(["Name", "Age", "Grade"])
writer.writerow(["Alice", 14, "A"])
writer.writerow(["Bob", 15, "B"])
# Reading from a CSV file
with open("students.csv", "r") as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(row)
6. Working with JSON Files
JSON is widely used for data exchange between applications.
import json
# Writing JSON to a file
data = {
"name": "Alice",
"age": 14,
"subjects": ["Math", "English", "Science"]
}
with open("data.json", "w") as jsonfile:
json.dump(data, jsonfile)
# Reading JSON from a file
with open("data.json", "r") as jsonfile:
loaded_data = json.load(jsonfile)
print(loaded_data["name"]) # Alice
7. Practice Exercises
- Create a text file
notes.txtand write 5 of your favorite quotes. - Create a CSV file
inventory.csvfor a shop with columns:Item,Quantity,Price. Read it and calculate total value. - Create a JSON file with your friends' details (
name,age,city) and load it back in Python. - Read a text file and count the number of words in it.