21.CSV & JSON
CSV (Comma-Separated Values) and JSON (JavaScript Object Notation) are two widely used formats for storing and exchanging data. CSV is a simple format used for tabular data, while JSON is a lightweight data-interchange format that is easy for humans to read and write, and easy for machines to parse and generate.
Working with CSV Files
Reading CSV Files
Python provides the built-in `csv` module to work with CSV files. Here’s how to read a CSV file:
import csv
with open(“data.csv”, newline=””) as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(row)
Writing CSV Files
You can also write data to a CSV file using the `csv` module:
import csv
data = [[“Name”, “Age”], [“Alice”, 30], [“Bob”, 25]]
with open(“output.csv”, “w”, newline=””) as csvfile:
writer = csv.writer(csvfile)
writer.writerows(data)
Working with JSON Files
Reading JSON Files
import json
with open(“data.json”) as jsonfile:
data = json.load(jsonfile)
print(data)
Writing JSON Files
You can write data to a JSON file using the `json` module:
import json
data = {“name”: “Alice”, “age”: 30}
with open(“output.json”, “w”) as jsonfile:
json.dump(data, jsonfile, indent=4)
Comparison of CSV and JSON
Feature | CSV | JSON |
Structure | Tabular (rows and columns) | Hierarchical (key-value pairs) |
Readability | Human-readable | Human-readable |
Complex Data | Not suitable | Suitable |
File Size | Smaller | Larger |
Use Case | Spreadsheets, simple data | APIs, configuration files |
Use Cases
– CSV is ideal for exporting and importing data from spreadsheets and databases.
– JSON is commonly used for data exchange between web clients and servers.
– JSON is preferred when working with nested or hierarchical data structures.
Best Practices
– Always handle file operations using context managers (`with` statement) to ensure proper resource management.
– Validate JSON data before processing to avoid runtime errors.
– Use `newline=”` when writing CSV files to avoid blank lines on some platforms.
– Use `indent` parameter in `json.dump()` for better readability.