How do I create a CSV file from database in Python?(如何从 Python 中的数据库创建 CSV 文件?)
问题描述
我有一个名为clients"的 Sqlite 3 和/或 MySQL 表..
I have a Sqlite 3 and/or MySQL table named "clients"..
使用 python 2.6,我如何创建一个名为 Clients100914.csv 的带有标题的 csv 文件?excel方言...
Using python 2.6, How do I create a csv file named Clients100914.csv with headers? excel dialect...
Sql 执行:select * 只提供表数据,但我想要带有标题的完整表.
The Sql execute: select * only gives table data, but I would like complete table with headers.
如何创建记录集以获取表头.表头应该直接来自不是用 python 编写的 sql.
How do I create a record set to get table headers. The table headers should come directly from sql not written in python.
w = csv.writer(open(Fn,'wb'),dialect='excel')
#w.writelines("header_row")
#Fetch into sqld
w.writerows(sqld)
这段代码让我打开文件并且没有标题.也无法弄清楚如何使用文件作为日志.
This code leaves me with file open and no headers. Also cant get figure out how to use file as log.
推荐答案
import csv
import sqlite3
from glob import glob; from os.path import expanduser
conn = sqlite3.connect( # open "places.sqlite" from one of the Firefox profiles
glob(expanduser('~/.mozilla/firefox/*/places.sqlite'))[0]
)
cursor = conn.cursor()
cursor.execute("select * from moz_places;")
with open("out.csv", "w", newline='') as csv_file: # Python 3 version
#with open("out.csv", "wb") as csv_file: # Python 2 version
csv_writer = csv.writer(csv_file)
csv_writer.writerow([i[0] for i in cursor.description]) # write headers
csv_writer.writerows(cursor)
PEP 249 (DB API 2.0) 有更多关于cursor.description.
这篇关于如何从 Python 中的数据库创建 CSV 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从 Python 中的数据库创建 CSV 文件?
基础教程推荐
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- 在多列上分布任意行 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- oracle区分大小写的原因? 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
