2016-04-28 77 views
0

我有一個字典文件,我想加載到一個csv文件,其中鍵是我的列,並且每次新數據讀入時,值都會繼續追加到新行。 我的代碼:python將字典數據加載到csv文件

with open ('master_result.csv','r+b')as csvFile: 
    header = next(csv.reader(csvFile)) 
    dict_writer = csv.DictWriter(csvFile,header, 0) 
    dict_writer.writerow(dict1) 

,但我得到

header = next(csv.reader(csvFile) 
StopIteration 

我無法找到問題。

+0

確定'master_result。 csv'不是空的? – alecxe

+2

你爲什麼在同一個文件中讀寫?程序啓動之前,文件包含什麼內容?什麼時候結束? –

回答

0

由於您的迭代(即您的文件)中沒有其他值,因此您的程序將拋出StopIteration錯誤。你能解決這個

一種方式是通過實施一些error handling

with open ('master_result.csv','r+b') as csvFile: 
    try: 
     # check if the necessary headers exist in your 
     # csvFile already. 
     header = next(csv.reader(csvFile)) 
     dict_writer = csv.DictWriter(csvFile, header) 
     dict_writer.writerow(dict1) 
    except StopIteration: 
     # If the headers don't already exist, 
     # use the keys of Dict1 to establish them. 
     header = dict1.keys() 
     dict_writer = csv.DictWriter(csvFile, header) 
     dict_writer.writeheader() 
     dict_writer.writerow(dict1) 

# 'master_result.csv' output if dict1 = {key1: value1, key2: value2, key3: value3}: 
# key1 key2 key3 
# value1 value2 value3 

你也可以換你with塊與for遍歷多個詞典(例如,類型的字典清單)進行迭代,幷包括所有的輸出文件中的值。這只是一個猜測,但我認爲這是你的意思是什麼:

...和值將保持每次在新的數據讀取附加到新行