【问题标题】:Python csv error : sequence expectedPython csv错误:预期序列
【发布时间】:2014-05-13 12:02:00
【问题描述】:

我使用psycopg2连接postgresql和python,这是我的脚本,

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

如何解决这个问题?

我在 Windows 8.1 x64 下使用 python 2.7.6 和 pyscripter。有什么建议可以给我,非常感谢!

【问题讨论】:

  • 能否提供完整的回溯?
  • 你为什么打开字节(二进制)文件? csv 文件是一个文本文件。
  • @Trimax:在 Python 2.x 中,csv 文件 IO 必须使用“rb”和“wb”。
  • @Lafada 我在帖子中添加了完整的回溯。

标签: python python-2.7 csv


【解决方案1】:
  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 文件。

或者如果你想在输出中有一行,那么不要使用 for 循环,而是使用

   writer.writerow(ars)

【讨论】:

  • 谢谢,您的回答很好,很有帮助,再次感谢!
猜你喜欢
  • 2012-04-22
  • 1970-01-01
  • 1970-01-01
  • 2014-09-05
  • 2011-02-08
  • 2012-09-05
  • 2012-12-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多