如何在Python中将sqlite导出为CSV而不作为列表格式化? [英] How to export sqlite to CSV in Python without being formatted as a list?

查看:1453
本文介绍了如何在Python中将sqlite导出为CSV而不作为列表格式化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我目前有的:

conn = sqlite3.connect(dbfile)
conn.text_factory = str ## my current (failed) attempt to resolve this
cur = conn.cursor()
data = cur.execute("SELECT * FROM mytable")

f = open('output.csv', 'w')
print >> f, "Column1, Column2, Column3, Etc."
for row in data:
  print >> f, row
f.close()

它创建一个带有输出的CSV文件像这样:

It creates a CSV file with output that looks like this:

Column1, Column2, Column3, Etc.
(1, u'2011-05-05 23:42:29',298776684,1448052234,463564768,-1130996322, None, u'2011-05-06 04:44:41')

我不希望行在括号中,也不需要引号,也不要在字符串之前使用'u'。我如何让它写的行到csv没有所有这一切?谢谢,

I don't want the rows to be in parentheses nor have quotes nor the 'u' before strings. How do I get it to write the rows to csv without all of this? Thanks,

推荐答案

您目前正在做的是打印出一个元组的Python字符串表示形式, code> str(row)。这包括引号和'u'和括号等。

What you're currently doing is printing out the python string representation of a tuple, i.e. the return value of str(row). That includes the quotes and 'u's and parentheses and so on.

而是要为CSV文件正确格式化数据。那么,请尝试 csv 模块 。它知道如何格式化CSV文件的内容,不足为奇。

Instead, you want the data formatted properly for a CSV file. Well, try the csv module. It knows how to format things for CSV files, unsurprisingly enough.

with open('output.csv', 'wb') as f:
    writer = csv.writer(f)
    writer.writerow(['Column 1', 'Column 2', ...])
    writer.writerows(data)

这篇关于如何在Python中将sqlite导出为CSV而不作为列表格式化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆