python如何保存数据,给出代码
时间: 2024-10-14 08:00:37 浏览: 22
Python数据分析实战源代码
5星 · 资源好评率100%
在Python中,有多种方式可以保存数据,常见的包括文件存储、数据库存储以及序列化技术。以下是几个常用的例子:
1. **文件存储** (文本文件、CSV、JSON等):
- 保存文本数据到文件:
```python
data = {"name": "John", "age": 30}
with open("data.txt", "w") as file:
file.write(str(data))
```
- 保存CSV文件:
```python
import csv
data = [['Name', 'Age'], ['John', 30]]
with open('data.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerows(data)
```
- 保存JSON文件:
```python
import json
data = {"key": "value"}
with open("data.json", "w") as file:
json.dump(data, file)
```
2. **数据库存储** (如SQLite、MySQL、PostgreSQL等):
- 使用sqlite3模块:
```python
import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute('''CREATE TABLE stocks
(date text, trans text, symbol text, qty real, price real)''')
c.execute("INSERT INTO stocks VALUES ('2023-01-01','BUY','AAPL',100,145.2)")
conn.commit()
conn.close()
```
3. **序列化库** (pickle, msgpack, or marshmallow):
- pickle库用于Python对象的序列化:
```python
import pickle
data = {'name': 'Alice'}
with open('data.pickle', 'wb') as handle:
pickle.dump(data, handle)
```
阅读全文