L16. 核心模块开发 (3):数据的归宿
Vibe Coding 宣言:数据如果只活在内存里,一断电就什么都没了。让它落地生根。
0. 为什么这一课至关重要? (Why It Matters)
- 持久化 (Persistence):这是把“程序”变成“系统”的关键一步。
- 给老板看:老板看不懂代码,但他看得懂 Excel 表格。
- 给未来看:历史数据是宝藏。把今天的数据存下来,明天你就能做趋势分析。
1. 目标 (Goal)
学会将处理后的数据保存为 CSV/Excel 文件,或者存入 SQLite 数据库。
2. 核心概念/装备/指令 (The Core)
2.1 文件存储 (The File)
- CSV:最通用的文本格式。谁都能打开。
- Excel:带格式的表格。给非技术人员看最好。
2.2 数据库 (The Database)
- SQLite:一个文件就是一个数据库。无需安装,Python 自带。最适合中小型项目。
- ORM (SQLAlchemy):用 Python 对象操作数据库,不用写 SQL 语句。
3. 实战演练 (Action)
Step 1: 存为 CSV/Excel
Pandas 自带神器:
python
df.to_csv('result.csv', index=False, encoding='utf-8-sig')
df.to_excel('result.xlsx', index=False)utf-8-sig:为了防止 Excel 打开乱码(这是 Windows 的坑)。
Step 2: 存入 SQLite
python
import sqlite3
# 1. 连接数据库 (如果不存在会自动创建)
conn = sqlite3.connect('data.db')
# 2. 存入 (Pandas 直接支持)
df.to_sql('products', conn, if_exists='replace', index=False)
# 3. 查询验证
cursor = conn.cursor()
cursor.execute("SELECT count(*) FROM products")
print(cursor.fetchone())Step 3: 封装 Storage 类
让 Claude 帮你写个 StorageManager 类:
python
class StorageManager:
def __init__(self, db_path='data.db'):
self.conn = sqlite3.connect(db_path)
def save_products(self, products_df):
products_df.to_sql('products', self.conn, if_exists='append')
def get_products(self):
return pd.read_sql('SELECT * FROM products', self.conn)4. 常见问题 (FAQ - Vibe Style)
Q: 存 CSV 乱码怎么办? A: 用 utf-8-sig。 如果还不行,用 Excel 的“数据导入”功能。
Q: SQLite 能存多少数据? A: 几百万条没问题。 超过这个量级,或者要多个人同时写,就得换 PostgreSQL 了。
Q: 每次运行都要清空旧数据吗? A: 看需求。 if_exists='replace' 是覆盖,'append' 是追加。一般追加比较好,加上时间戳字段。
5. 验收标准 (Definition of Done)
- 运行程序后,本地生成了
result.csv。 - 用 Excel 打开 CSV,内容显示正常(无乱码)。
- 生成了
data.db文件,且能查到数据。
Next Mission: L17. 异常处理专项:让程序不死