2013-08-26 123 views
1

我是新的python,但經過3天的閱讀和找到解決方案沒有成功,我迷路了。for循環for循環,python,csv讀寫器

我得到了與數據(id,user_id ...)的MySQL表。我連接到db,讀取user_id並將數據保存到數組「user」中。然後我用很多行和列(user_id,名稱,郵件,電話,地址...)打開csv文件。在下一步我比較來自數據庫的user_id與csv文件中的user_id匹配。如果答案是肯定的,那麼我在另一個csv文件中寫入這一行。

問題是我的代碼僅適用於第一個id_user。請,你能幫我嗎?

實施例的表:

table in db: 
id  user_id 
1  318604 
2  318624 

csv文件:

318604; John; [email protected] 
318604; 053746; USA 
318624; Lucy; [email protected] 
318624; 058839 Sweeden 
318630; Luke; [email protected] 

預期結果在新文件:

318604; John; [email protected] 
318604; 053746; USA 
318624; Lucy; [email protected] 
318624; 058839 Sweeden 

代碼:

cur = con.cursor() 
with open('input.csv', mode='rb') as f: 
    reader = csv.reader(f, delimiter=';') 
    with open('output.csv', mode='a') as w: 
     writer = csv.writer(w) 
     with con:    
      cur.execute("SELECT user_id FROM users") 
      user=cur.fetchall()    
      for i in range(len(user)):        
       for row in reader: 
        if(user[i][0]==row[0]): 
         writer.writerow(row) 
con.close() 

回答

2

您需要重新打開input.csv文件。當你瀏覽文件的每一行而不重新打開它時,你的文件將始終在文件的最後一行。爲了解決輸入文件的這一舉動開到for user循環:

cur = con.cursor() 
with open('output.csv', mode='a') as w: 
    writer = csv.writer(w) 
    with con:    
     cur.execute("SELECT user_id FROM users") 
     user=cur.fetchall()    
     for i in range(len(user)): 
      with open('input.csv', mode='rb') as f: 
       reader = csv.reader(f, delimiter=';')        
       for row in reader: 
        if(user[i][0]==row[0]): 
         writer.writerow(row) 
con.close() 

我使用此代碼測試它:

從您的數據庫,而不是輸出
import csv 
user = [[1,318604],[2,318624]] 
with open('output.csv', mode='a') as w: 
    writer = csv.writer(w)  
    for i in range(len(user)): 
     with open('input.csv', mode='rb') as f: 
      reader = csv.reader(f, delimiter=';')        
      for row in reader: 
       if(str(user[i][1])==row[0]): 
        writer.writerow(row) 

我用它整數列表。所以我需要將user[i][1]轉換爲字符串。另外user[i][0]id,當user[i][1]user_id,不知道它對你的數據庫輸出是否一樣。

輸出:

318604, John, [email protected] 
318604, 053746, USA 
318624, Lucy, [email protected] 
318624, 058839 Sweeden 
+0

謝謝你,這是一種魅力! – djpiky

+0

如果答案適合您,請將其標記爲[accepted](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) – ton1c

-1

我想你,因爲你比較整數,字符串(從CSV)取變量的格式的照顧,試試這個:

cur = con.cursor() 
with open('input.csv', mode='rb') as f: 
    reader = csv.reader(f, delimiter=';') 
    with open('output.csv', mode='a') as w: 
     writer = csv.writer(w) 
     with con:    
      cur.execute("SELECT user_id FROM users") 
      users=cur.fetchall()    
      for u in user:        
       for row in reader: 
        if(str(u[0])==str(row[0])): 
         writer.writerow(row) 

似乎對工作對我來說

+0

然後爲什麼它在輸出中第一次打印只有第一個'user_id'的文件? – ton1c

+0

我沒有用數據庫進行測試,事實上,我也用列表測試。嘗試迭代記錄集,我編輯我的答案 –