python从字典写入文件 [英] python write to file from dictionary

查看:61
本文介绍了python从字典写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 新手,我知道这段代码非常简单并且缺少一些语句,实际上我需要从字典写入文件.此代码运行但仅将 dict 中的最后一项写入文件 "heba6677..." .感谢您的帮助.

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()

推荐答案

如果您想继续向文件添加行,请使用 a 模式打开它,如 文档:

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)

使用 w 作为模式意味着 writing:您的文件将被覆盖.

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

这篇关于python从字典写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆