2012-09-26 84 views
2

我是新來的Python,我知道這段代碼非常簡單,缺少一些語句,實際上我需要從字典中寫入文件。此代碼可以運行,但只能將字典中的最後一項寫入文件"heba6677..."。謝謝你的幫助。python寫入文件從字典

ab={'engy':'011199887765', 
    'wafa2':'87878857578', 
    'heba':'6677553636'} 
for name, mobile in ab.items(): 
    print ('Contact %s at %s' % (name, mobile)) 
    f=open('D:\glo.txt','w') 
    f.write(name) 
    f.write(mobile) 
f.close() 

回答

7

如果你想不斷增加線條到您的文件,與a模式打開它,在documentation描述:

for (name, mobile) in ab.iteritems(): 
    with open(...., "a") as f: 
     print ('Contact %s at %s' % (name, mobile)) 
     f.write(name) 
     f.write(mobile) 

使用w的模式意味着writing:您的文件將被覆蓋。

+0

它的工作原理thaaaaaaaaanx –

2

每次在w模式下打開文件時,其先前的內容都將被刪除。所以你只應該在循環之前做一次。最重要的是,與with聲明做到這一點:

ab={'engy':'011199887765', 
    'wafa2':'87878857578', 
    'heba':'6677553636'} 
with open('D:\glo.txt','w') as f: 
    for name, mobile in ab.items(): 
     print ('Contact %s at %s' % (name, mobile)) 
     f.write(lis) 
     f.write(mobile) 

另外,我不知道是什麼lis是的,但我會認爲這是在正確的地方。請注意,您的代碼只能將lis數字寫入文件,而不是名稱。 lis在循環中不會更改,因此它在每次迭代中都是相同的。

+0

不要忘記在文件輸出中添加一些空格字符。 – moooeeeep

+0

@moooeeeep如果不是,我會留給OP找出。 –

+0

:)其實我忘了在發帖之前將名稱改爲lis :) thanx的幫助 –