我寫了一個python腳本來運行PostgreSQL中的sql行,環路與數字CSV文件
import sys, os, math
os.chdir(r'C:\Users\Heinz\Desktop')
print os.getcwd()
#set up psycopg2 environment
import psycopg2
#shortest_path module
query = """
select *
from shortest_path ($$
select
gid as id,
source::int4 as source,
target::int4 as target,
cost::double precision as cost,
rcost::double precision as reverse_cost
from network
$$, %s, %s, %s, %s
)
"""
#make connection between python and postgresql
conn = psycopg2.connect("dbname = 'test' user = 'postgres' host = 'localhost' password = 'xxxx'")
cur = conn.cursor()
#count rows in the table
cur.execute("select count(*) from network")
result = cur.fetchone()
k = result[0] + 1 #number of points = number of segments + 1
#run loops
#import csv module
import csv
import tempfile
element = []
i = 1
l = 1
filename = 'pi_value.csv'
with open(filename, 'wb') as f:
while i <= k:
while l <= k:
cur.execute(query, (i, l, True, True))
element = cur.fetchall()
product = sum([a[-1] for a in element[:-1]])
writer = csv.writer(f, delimiter = ',')
writer.writerow([product])
element = []
l = l + 1
l = 1
i = i + 1
你可以看到,我用迭代器從我到K(和L到K)做while循環,現在我得到一個csv文件,其中包含我希望迭代器i和l爲的數字。例如,這裏的csv文件,
我想迭代器遍歷在最裏面使用從第一個開始的每一行的數字,比如while循環,L = 6,L = 31,l = 28,...,l = 17,i也是從6開始的,但是隻有當我移動到17並返回到l = 6時才移動到i = 31,依此類推。
如何寫附加線讀取該CSV文件,並讓while循環迭代運行循環在文件中的數字?
更新#1
我試過這個,
element = []
with open('tc_sta_id.csv') as f1, open('pi_value.csv', 'wb') as f2:
csvs = csv.reader(f1)
col_num = 0
rows = list(csvs)
k = len(rows)
for row in csvs:
i = row[col_num]
l = row[col_num]
while i <= k:
while l <= k:
cur.execute(query, (i, l, True, True))
element = cur.fetchall()
product = sum([a[-1] for a in element[:-1]])
writer = csv.writer(f2, delimiter = ',')
writer.writerow([product])
element = []
l = l + 1
l = row[col_num]
i = i + 1
腳本運行良好,但輸出csv文件中都有空白,請給我建議解決這個問題!
你確定從查詢中得到了什麼嗎? – yemu
是的,但我不知道如何循環查詢中的兩個迭代器。 – Heinz
我不知道你想做什麼,但也許你應該閱讀兩次csv並獨立迭代 – yemu