Mastering Storing and Retrieving Structured Data in Python
Structured data is essential for many applications, from simple file storage to complex database-driven systems. In this guide, you'll learn how to handle structured data effectively in Python.
What is Structured Data?
Structured data refers to information that is organized in a predictable format. It's often stored in rows and columns, similar to a spreadsheet or database table. Common examples include:
- JSON files
- CSV files
- Relational databases
Python provides robust libraries to interact with these formats seamlessly.
Working with JSON Data
JSON (JavaScript Object Notation) is widely used for storing and exchanging data. Python includes the built-in json module to handle JSON data.
Saving Data to a JSON File
import json
data = {
"name": "Alice",
"age": 30,
"city": "New York"
}
with open('data.json', 'w') as file:
json.dump(data, file)This code creates a JSON file named data.json containing the dictionary data.
Loading Data from a JSON File
with open('data.json', 'r') as file:
loaded_data = json.load(file)
print(loaded_data)The above snippet reads the JSON file and converts it back into a Python dictionary.
Handling CSV Files
CSV (Comma-Separated Values) is another popular format for structured data, especially for tabular data.
Writing to a CSV File
import csv
data = [
['Name', 'Age', 'City'],
['Alice', 30, 'New York'],
['Bob', 25, 'Los Angeles']
]
with open('data.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)This script writes a list of lists into a CSV file.
Reading from a CSV File
with open('data.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)The output will display each row of the CSV file.
Using Databases for Structured Data
For larger datasets, relational databases like SQLite are ideal. Python’s sqlite3 library allows you to create, query, and manage SQLite databases.
Creating a Table and Inserting Data
import sqlite3
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS users
(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')
cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", ('Alice', 30))
conn.commit()
conn.close()This example demonstrates creating a table and inserting a record.
Querying Data from the Database
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
for row in rows:
print(row)
conn.close()This code fetches and prints all records from the users table.
By mastering these techniques, you'll be able to store and retrieve structured data with ease!