2014-06-13 34 views
1

我寫了一個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文件中都有空白,請給我建議解決這個問題!

+0

你確定從查詢中得到了什麼嗎? – yemu

+0

是的,但我不知道如何循環查詢中的兩個迭代器。 – Heinz

+1

我不知道你想做什麼,但也許你應該閱讀兩次csv並獨立迭代 – yemu

回答

1

由於您的問題已經改變了不少的列數自從一開始,我只是把它作爲一個單獨的答案加入。因此,這是專門針對您的更新1的答案。

您的while循環的條件是錯誤的。您的條件基於您csv中的行數(在您的示例中爲8)。你將它與csv中的數字進行比較(如6,31,...)。這意味着每當你點擊第二個數字(31> 8)時,while循環就會停止。此外,你沒有跳到你的csv的下一個元素,但你只需加1.我沒有試過運行你的代碼,但我認爲你的循環結束了:i = 6,7,8,l = 6,7 ,i的每個值爲8。然後它嘗試31,立即停止,因爲它與其餘的(他們都在8以上)。

我不完全確定你想要什麼,因爲你似乎一直希望使用額外的while循環來處理某些事情,而且我不確定你想要使用它們(在你的問題中找不到它,只有您的問題中的所有內容都只針對循環)。

我也不確定我和我是否來自同一個csv或沒有。我給你一個解決方案,你可以很容易地讓我和我來自不同的csvs,但我在一開始就設置它們來自同一個。如果它們來自同一個csv,那麼你不能只用同一個迭代器來嵌套for循環,所以我們會欺騙並將它們提取到一個列表中(我用一個簡單的例子來測試它)。

rows = list(csvs) #convert to a list to avoid problems with iterating over the same iterator 
csv_for_i = rows 
csv_for_l = rows 
for row_i in csv_for_i: 
    i = row_i[col_num] 
    for row_l in csv_for_l: 
     l = row_l[col_num] 
     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 = [] 

讓我知道這是否工作。如果是這樣,接受答案,我會考慮如何使問題和答案變得更適合堆棧溢出的東西。目前,這裏實際上有很多問題和答案,這讓其他人在尋找答案時感到困惑。


僅供參考,關於迭代器(使用csv製作,但適用於所有迭代器)的陷阱小例子。

import csv 

# test.csv contents: 
# 
#6 
#31 
#17 

print 'Case 1:' 
with open('test.csv') as f1: 
    csv1 = csv.reader(f1) 
    csv2 = csv.reader(f1) 
    for el1 in csv1: 
     for el2 in csv2: 
      print el1, el2 
# Results 
# 
#['6'] ['31'] 
#['6'] ['17'] 

print 'Case 2:' 
with open('test.csv') as f1: 
    csvs = csv.reader(f1) 
    rows = list(csvs) 
    for el1 in rows: 
     for el2 in rows: 
      print el1, el2 
# Results 
# 
#['6'] ['6'] 
#['6'] ['31'] 
#['6'] ['17'] 
#['31'] ['6'] 
#['31'] ['31'] 
#['31'] ['17'] 
#['17'] ['6'] 
#['17'] ['31'] 
#['17'] ['17'] 

print 'Case 3:' 
with open('test.csv') as f1, open('test.csv') as f2: 
    for el1 in csv.reader(f1): 
     for el2 in csv.reader(f2): 
      print el1, el2 
# Results 
# 
#['6'] ['6'] 
#['6'] ['31'] 
#['6'] ['17'] 

print 'Case 4:' 
with open('test.csv') as f1, open('test.csv') as f2: 
    csv1 = csv.reader(f1) 
    csv2 = csv.reader(f2) 
    for el1 in csv1: 
     for el2 in csv2: 
      print el1, el2 
# Results 
# 
#['6'] ['6'] 
#['6'] ['31'] 
#['6'] ['17'] 
0

我使用簡單的python功能爲您做了簡短的測試。

f = open('test.csv') 
csvlines = f.readlines() 
f.close() 
numbers = [int(n.split(',')[0]) for n in csvlines] 

您可能需要用';'代替','或其他的東西取決於你的操作系統的區域設置。

簡短說明: csvlines將包含csv的行作爲字符串f.e. ['1,a,一些文字','2,b,一些其他文字']。您將通過每條線路並在線路上呼叫拆分,例如'1,a,some text'.split(',')會給['1','a','一些文字']。您的第一列然後需要被轉換爲整數,因爲它目前仍然是一個字符串。

使用在你的代碼(編輯成問題被編輯):

for i in numbers: 
    if(i<k): 
     for l in numbers: 
      # not sure what your constraint on k is, but you can stop iterating 
      # through the numbers with a simple if 
      if(l<k): 
       #do work (you can use i an l here, they will automatically 
       # take the next value each iteration of the for loop 
       #(try print i, l for example): 6,6; 6,31; ...; 6,17; 31,6; 31,31 
+0

感謝您的回覆,但我在我的文章中犯了一個錯誤,我已經糾正它。你能否給我答覆糾正後的帖子?非常感謝你。 – Heinz

+0

編輯:-)(讓我知道它是否有效)。 – HSquirrel

+0

我試過了,但沒有用,而且我編輯了我的帖子,如果你有想法,請告訴我,非常感謝! – Heinz

1

爲col_num是在你有你的I值

with open('yourfile') as file: 
    csv = csv.reader(file) 
    next(csv) # skip the header 
    col_num = 0 
    for row in csv: 
     i = row[col_num] 
     while i <= k: 
      cur.execute(query, (i, 100000000000, True, True)) 
      rs.append(cur.fetchall()) 
      i = i + 1 
+0

謝謝你的回覆,但是我在開始的時候在我的文章中輸入了錯誤的描述,現在我已經編輯了它,如果你有時間,請給我建議,非常感謝。 – Heinz