写标题&查询到csv

时间:2017-03-28 16:01:09

标签: python csv psycopg2

我正在尝试将查询结果从postgresql保存到csv文件中,但csv文件有时会缺少标题,但会写入查询的所有详细信息。

import psycopg2
import csv

try:
    conn = psycopg2.connect(database = '', user = '', host = '', password = '')
except:
    print ("I am unable to connect to the database")

cursor = conn.cursor()

query = """select * from"""

cursor.execute(query)

result = cursor.fetchall()

with open("kiker.csv","wb") as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames = ["Builder", "Subdivision", "Spec", "Build", "Cancel", "Price", "Sq_Ft", "PPSF", "Realtor", "Project ID"], extrasaction = 'ignore')
    writer.writeheader()
    writer.writerow(result)

print "Query 1 Created"

错误:

Traceback (most recent call last):
  File "C:\\connecting.py", line 45, in   <module>
    writer.writerow(result)
  File "C:\Python27\lib\csv.py", line 152, in writerow
    return self.writer.writerow(self._dict_to_list(rowdict))
  File "C:\Python27\lib\csv.py", line 149, in _dict_to_list
    return [rowdict.get(key, self.restval) for key in self.fieldnames]
AttributeError: 'list' object has no attribute 'get'

我尝试了以下两种方法,但它们都无法包含postgresql中的头信息。

c = csv.writer(open("kiker.csv","wb"))

for row in result:
    c.writerow(row)

fp = open("kiker.csv","wb")
myFile = csv.writer(fp)
myFile.writerows(result)
fp.close()

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

我用熊猫来解决这个问题。工作就像一种享受。

cursor.execute(query)

result = cursor.fetchall()

first = pd.DataFrame(result, columns = ["Builder","Subdivision","Spec","Build","Cancel","Price","Sq_Ft","PPSF","Realtor","Project ID"])

first.to_csv("kiker.csv",index = False)

答案 1 :(得分:0)

DictWriter期待dicts,而不是元组:https://docs.python.org/3.6/library/csv.html#writer-objects