Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
127 views
in Technique[技术] by (71.8m points)

python write to file from dictionary

I'm new with Python and I know that piece of code is very simple and lacks some statements, actually I need to write to file from dictionary. This code runs but only writes the last item in dict to the file which is "heba6677..." . Thanks for your help.

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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to keep adding lines to your file, open it with the a mode, as described in the 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)

Using w as mode means writing: your file will be overwritten.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...