python数据导出方法
时间: 2023-10-24 20:17:21 浏览: 156
Python中常用的数据导出方法有以下几种:
1. CSV文件导出:使用csv模块,可以将数据导出为CSV格式的文件,方便Excel等软件进行处理。示例代码如下:
```
import csv
data = [['name', 'age', 'gender'], ['John', '20', 'male'], ['Jane', '25', 'female']]
with open('data.csv', 'w', newline='') as file:
writer = csv.writer(file)
for row in data:
writer.writerow(row)
```
2. Excel文件导出:使用openpyxl模块,可以将数据导出为Excel格式的文件。示例代码如下:
```
from openpyxl import Workbook
data = [['name', 'age', 'gender'], ['John', '20', 'male'], ['Jane', '25', 'female']]
wb = Workbook()
ws = wb.active
for row in data:
ws.append(row)
wb.save('data.xlsx')
```
3. JSON文件导出:使用json模块,可以将数据导出为JSON格式的文件。示例代码如下:
```
import json
data = {'name': 'John', 'age': 20, 'gender': 'male'}
with open('data.json', 'w') as file:
json.dump(data, file)
```
4. SQL数据库导出:使用pymysql、sqlite3等模块,可以将数据导出为SQL数据库格式的文件。示例代码如下:
```
import pymysql
data = [['John', 20, 'male'], ['Jane', 25, 'female']]
conn = pymysql.connect(host='localhost', user='root', password='password', database='test')
cursor = conn.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS users (name VARCHAR(20), age INT, gender VARCHAR(10))')
for row in data:
cursor.execute('INSERT INTO users (name, age, gender) VALUES (%s, %s, %s)', row)
conn.commit()
cursor.close()
conn.close()
```
阅读全文