Python csv:使用不同的变量名来存储列表,然后逐行导出

时间:2014-04-02 18:22:33

标签: python python-2.7 csv

这是我的python脚本,用于在postgresql中获取sql结果,

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

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

conn.close()

import csv

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

我想获取下面的csv文件,

enter image description here

即,将第一行分配给ars(0),将第二行分配给ars(1),将第三行分配给ars(2),我使用 vars()[str(j) ] = ars 使变量名ars(j)在while循环中增加,但我的输出只在第一行,

enter image description here

(部分观点)

我应该在脚本中修改哪里?

我在Windows 8.1 x64下使用python 2.7.6和pyscripter。随意给我任何建议,非常感谢!

0 个答案:

没有答案