2015-04-27 80 views
1

我有一本字典,我想使用此代碼將數據寫入文件currencies.csv: 爲字典的代碼是節省字典到CSV文件

def _fetch_currencies(): 
    response =urllib.request.urlopen('http://www.maths.manchester.ac.uk/~vsego/python/currencies.json') 
    html = response.read().decode("utf-8") 

    currencies = json.loads(html) 
    pprint(currencies) 

def _save_currencies(currencies): 
    with open(('currencies.csv'), 'wt') as my_csv: 
     csv_writer = csv.writer(my_csv, delimiter=',') 
     csv_writer.writerow(["code","name"]) 
     for key,value in currencies.items(): 
      csv_writer.writerow([key,value]) 

_save_currencies(_fetch_currencies()) 

當我回到我的代碼得到錯誤信息

'AttributeError: 'NoneType' object has no attribute 'items'' 

我該如何解決這個錯誤?

+1

什麼是貨幣? –

+0

我的Python有點生疏,但'_fetch_currencies()'不返回任何東西。因此,它的調用應該分別評估爲'null'或'NoneType',這就是交給'_save_currencies()'的東西。由於'NoneType'沒有'items()'方法,拋出異常。 –

回答

1

您需要_fetch_currencies()返回:

def _fetch_currencies(): 
    response =urllib.request.urlopen('http://www.maths.manchester.ac.uk/~vsego/python/currencies.json') 
    html = response.read().decode("utf-8") 
    return json.loads(html) # <- return 

你默認情況下不返回任何值,所以Python回報None所以當你通過_fetch_currencies()_save_currencies你逝去的None

您也可以通過dict.items並調用csv.writerows

def _save_currencies(currencies): 
    with open(('currencies.csv'), 'wt') as my_csv: 
     csv_writer = csv.writer(my_csv, delimiter=',') 
     csv_writer.writerow(["code","name"]) 
     csv_writer.writerows(currencies.items()) 
0

的錯誤是因爲你從沒有任何一本字典請求鍵。原因是_fetch_currencies()沒有返回語句。

def _fetch_currencies(): 
    response =urllib.request.urlopen('http://www.maths.manchester.ac.uk/~vsego/python/currencies.json') 
    html = response.read().decode("utf-8") 

    currencies = json.loads(html) 
    return currencies 

無論如何,這應該工作:

currencies = {} 
for key,value in currencies.items(): 
    print key, value 

如果這是行不通的:

currencies = None 
for key,value in currencies.items(): 
    print key, value