2015-08-14 14 views
0

我有一個名爲「list」的列表。它包含兩個字典。我正在以dict [count],dict [count + 1]的形式訪問這些字典。Python:如何將某個鍵的值寫入文件?

現在我必須檢查一個關鍵是作爲版本。然後我寫代碼爲

filename = "output.txt" 
fo = open(filename, "a") 
for key1,key2 in zip(dict[count].keys(),dict[count+1].keys()): 
    if key1 == 'version': 
     # print "value of version:", (dict[count])[key] 
     fo.write("value of version:",(dict[count])[key]) 
    if key2 == 'version': 
     # print "value of version:", (dict[count+1])[key] 
     fo.write ("value of version:", (dict[count+1])[key2]) 

這裏我能夠打印版本的值,但我無法寫入文件。

Errror:類型錯誤:功能恰恰1個參數(2給出)

+2

fo.write(「value of version:」** + **(dict [count])[key]) – deathangel908

+0

Thanks deathangle908。其工作 – SSH

+1

避免使用字典和列表作爲變量名稱。這是危險的,會帶來不希望的結果。 – lima

回答

0

你不能做file.write()像你這樣print()在多個對象傳遞給打印由逗號分隔(作爲一個元組),這是你的原因正在出錯。您應該使用string.format()正確地格式化您的字符串。

示例 -

filename = "output.txt" 
fo = open(filename, "a") 
for key1,key2 in zip(dict[count].keys(),dict[count+1].keys()): 
    if key1 == 'version': 
     # print "value of version:", (dict[count])[key] 
     fo.write("value of version:{}".format(dict[count][key1])) 
    if key2 == 'version': 
     # print "value of version:", (dict[count+1])[key] 
     fo.write ("value of version:()".format(dict[count+1][key2])) 

而且,不知道爲什麼你需要做的拉鍊,所有的,你可以簡單地做 -

filename = "output.txt" 
fo = open(filename, "a") 
if 'version' in dict[count]: 
    fo.write("value of version:{}".format(dict[count]['version'])) 
if 'version' in dict[count+1]: 
    fo.write("value of version:{}".format(dict[count+1]['version'])) 
3

fo.write()函數只能有一個論據。你提供了兩個參數,所以它不起作用。請參閱下面的行並使用它。

fo.write("value of version:%s"%(dict[count])[key]) 
fo.write ("value of version:%s"%(dict[count+1])[key2]) 
相關問題