2014-04-02 43 views
3

我用psycopg2連接PostgreSQL和蟒蛇,這是我的腳本,Python的CSV錯誤:序列預計

import sys 

#set up psycopg2 environment 
import psycopg2 

#driving_distance module 
query = """ 
    select * 
    from driving_distance ($$ 
     select 
      gid as id, 
      start_id::int4 as source, 
      end_id::int4 as target, 
      shape_leng::double precision as cost 
     from network 
     $$, %s, %s, %s, %s 
    ) 
""" 

#make connection between python and postgresql 
conn = psycopg2.connect("dbname = 'TC_routing' user = 'postgres' host = 'localhost' password = '****'") 
cur = conn.cursor() 

#count rows in the table 
cur.execute("select count(*) from network") 
result = cur.fetchone() 
k = result[0] + 1 

#run loops 
rs = [] 
i = 1 
while i <= k: 
    cur.execute(query, (i, 1000000, False, False)) 
    rs.append(cur.fetchall()) 
    i = i + 1 

h = 0 
ars = [] 
element = list(rs) 
while h <= 15: 
    rp = element[0][h][2] 
    ars.append(rp) 
    h = h + 1 

print ars 
conn.close() 

輸出是好的,

[0.0, 11810.7956476379, 16018.6818979217, 18192.3576530232, 21507.7366792666, 25819.1955059578, 26331.2523709618, 49447.0908955008, 28807.7871013087, 39670.8579371438, 42723.0239515299, 38719.7320396044, 38265.4435766971, 40744.8813155033, 43770.2158657742, 46224.8748774639] 

,但如果我添加下面的一些行爲了結果導出爲CSV文件,我得到這個錯誤,

import csv 

with open('test.csv', 'wb') as f: 
    writer = csv.writer(f, delimiter = ',') 
    for row in ars: 
     writer.writerow(row) 

[0.0, 11810.7956476379, 16018.6818979217, 18192.3576530232, 21507.7366792666, 25819.1955059578, 
26331.2523709618, 49447.0908955008, 28807.7871013087, 39670.8579371438, 42723.0239515299, 38719.7320396044, 38265.4435766971, 40744.8813155033, 43770.2158657742, 46224.8748774639] 

Traceback (most recent call last): 
    File "C:/Users/Heinz/Desktop/python_test/distMatrix_test.py", line 54, in <module> 
    writer.writerow(row) 
Error: sequence expected 

如何解決這一問題?

我使用Python 2.7.6和pyscripter在Windows 8.1 x64的工作。隨時給我任何建議,非常感謝!

+0

請你提供完整的追蹤? – Nilesh

+0

爲什麼你打開字節(二進制)文件?一個csv文件是一個文本文件。 – Trimax

+0

可能重複http://stackoverflow.com/questions/12396284/csv-error-sequence-expected-python – zhangjon

回答

5
import csv 

    with open('test.csv', 'wb') as f: 
    writer = csv.writer(f, delimiter = ',') 
    for row in ars: 
     writer.writerow(row) 

ars只是一個列表。所以你的for循環不會從ars中提取一行。它從ars列表中獲取一個元素,並嘗試將其作爲一行寫入。

嘗試用

 for row in ars: 
     writer.writerow([row]) 

這取代它會寫的每個元素爲csv文件一行。

或者如果u希望有一個單列作爲輸出,那麼就是不使用循環,而使用

writer.writerow(ars) 
+0

謝謝你,你的回答很好,非常有幫助,再次感謝! – Heinz