2016-06-01 43 views
-1

我無法弄清楚我在這段代碼中做了什麼錯誤。它似乎陷入了無限循環,我必須殺死這個過程。最後,這段代碼將用於將文件轉換爲Geojson格式,但是在我開始寫Geojson之前,我想確保我可以打開並追加到字典中。從csv文件寫入列表的問題

我發現的是,在我嘗試將csv文件附加到列表並打印出列表(第23行,注意此打印行僅用於幫助我解決問題)中,只有1一行數據(應該有更多的數據,可能是20-30行不同的列長度。是的,我已經檢查了輸入文件)。我也嘗試在另一個程序上運行csv輸入,並且沒有問題,所以我懷疑問題在我寫的代碼中。

感謝您的任何幫助。

import csv 

def main(): 
    try: 
     strFOLDER = (r'/Users/Smithy/Documents/Pycharm/' + '/') 
     strFILE = raw_input("Enter the name of file ") 
     my_file = strFOLDER + strFILE 
    except IOError: 
     print 'Cannot read/locate file error' 

    try: 
     fp = open(my_file, 'rU') 
     my_data = csv.reader(fp) 
    except IOError: 
     print 'Cannot read/locate file error' 

    my_list = [] 
    my_dictionary = {} 

    for row in my_data: 
     my_list.append(row) 
     print my_list 
     list_len = len(my_list) 
     num_count = 0 
     while num_count < list_len: 
      if (num_count < (list_len-2)): 
       my_dictionary['name'] = [1] 
       my_dictionary['location'] = ([num_count+2], [num_count+3]) 
       my_list.append(my_dictionary) 
       num_count+=2 

main() 
+0

嘗試在if語句之外移動numcount + = 2。 – TheLazyScripter

+0

我還假設mydictionary = {}應該放在for循環中,以確保它被每行覆蓋 – TheLazyScripter

回答

0

在你while循環,如果(num_count>(list_len-2)),所以這個循環還沒有結束,你什麼也不做,只顯示第一行。

更準確地說,當你將第一行追加到my_list時,這個長度是1. if子句變成if (num_count < (1 - 2)),這顯然不會發生。

0

你被困在while循環中。

你的問題是,num_count+=2永遠不會發生,除非num_count < (list_len-2)恰好是真實的。 list_len等於1您第一次追加到它,因此num_count永遠不會增加。