我有一个包含10个表的数据库:(日期,日期,月份,年份,pcp1,pcp2,pcp3,pcp4,pcp5,pcp6),每列有41年的数据集。日,月和年列是" Null"因为我将在导出csv文件中的表后添加它们并且我做了这部分,但格式不正确,因为每列必须分别分开。
这是我的数据库示例:
date day month year pcp1 pcp2 pcp3 pcp4 pcp5 pcp6
1.01.1979 0.431 2.167 9.375 9.375 0.431 9.375
2.01.1979 1.216 2.583 9.162 9.162 1.216 9.162
3.01.1979 4.041 9.373 23.169 23.169 4.041 23.169
4.01.1979 1.799 3.866 8.286 8.286 1.799 8.286
5.01.1979 0.003 0.051 0.342 0.342 0.003 0.342
6.01.1979 2.345 3.777 7.483 7.483 2.345 7.483
7.01.1979 0.017 0.031 0.173 0.173 0.017 0.173
我想获得上面的所有表格。但是,我得到了以下输出:
Column 1,Column 2,Ellipsis
1979-01-01,,,,0.431,2.167,9.375,9.375,0.431,9.375
1979-01-02,,,,1.216,2.583,9.162,9.162,1.216,9.162
1979-01-03,,,,4.041,9.373,23.169,23.169,4.041,23.169
1979-01-04,,,,1.799,3.866,8.286,8.286,1.799,8.286
1979-01-05,,,,0.003,0.051,0.342,0.342,0.003,0.342
有一些问题。首先,标题不存在,其次是跳过另一行(1到3)而不是(1到2),最后所有数据在column1下汇总。
我的代码是:
import csv
import sqlite3
conn=sqlite3.connect("pcpnew6.db")
c=conn.cursor()
data = c.execute("SELECT * FROM pcp3")
with open('output.csv', 'w') as f:
writer = csv.writer(f)
writer.writerow(['Column 1', 'Column 2', ...])
writer.writerows(data)
答案 0 :(得分:3)
以下是我的问题的答案,并结合Jean-FrançoisFabre发布的代码,感谢他的帮助。
import sys
import sqlite3
import csv
conn=sqlite3.connect("pcpnew6.db")
c=conn.cursor()
conn.row_factory=sqlite3.Row
crsr=conn.execute("SELECT * From pcp3")
row=crsr.fetchone()
titles=row.keys()
data = c.execute("SELECT * FROM pcp3")
if sys.version_info < (3,):
f = open('output.csv', 'wb')
else:
f = open('output.csv', 'w', newline="")
writer = csv.writer(f,delimiter=';')
writer.writerow(titles) # keys=title you're looking for
# write the rest
writer.writerows(data)
f.close()
这里是代码输出:
date day month year pcp1 pcp2 pcp3 pcp4 pcp5 pcp6
1.01.1979 0.431 2.167 9.375 9.375 2.167 0.431
2.01.1979 1.216 2.583 9.162 9.162 2.583 1.216
3.01.1979 4.041 9.373 23.169 23.169 9.373 4.041
4.01.1979 1.799 3.866 8.286 8.286 3.866 1.799
5.01.1979 0.003 0.051 0.342 0.342 0.051 0.003
6.01.1979 2.345 3.777 7.483 7.483 3.777 2.345
答案 1 :(得分:2)
description
属性返回最后一个查询表名称,因此它应该可以正常工作\r
(回车符号)。它在python 2和python 3之间的处理方式不同:;
csvs =&gt;您必须指定分号分隔符或Excel在一列上打开它。查看我的更改:
在python 3中(无法以二进制形式打开文本文件):
with open('output.csv', 'w', newline="") as f:
writer = csv.writer(f,delimiter=';')
根据文件 writer.writerows(数据)
在python 2中(换行选项不存在):
with open('output.csv', 'wb') as f:
writer = csv.writer(f,delimiter=';')
writer.writerows(data)
编辑:python 2/3兼容片段,标题行:
import sys
if sys.version_info < (3,):
f = open('output.csv', 'wb')
else:
f = open('output.csv', 'w', newline="")
writer = csv.writer(f,delimiter=';')
first_item = next(data) # get first item to get keys
writer.writerow(first_item.keys()) # keys=title you're looking for
writer.writerow(first_item)
# write the rest
writer.writerows(data)
f.close()
答案 2 :(得分:0)
或者使用熊猫。
import pandas
rows = cur.fetchall()
df = pandas.DataFrame.from_records(rows)