【问题标题】:python write to file from dictionarypython从字典写入文件
【发布时间】:2012-09-26 09:51:13
【问题描述】:

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

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

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    如果您想继续向文件中添加行,请使用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:您的文件将被覆盖。

    【讨论】:

      【解决方案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 在循环中不会改变,所以每次迭代都一样。

      【讨论】:

      • 不要忘记在文件输出中添加一些空白字符。
      • @moooeeeep 也许lis 中有一些 :) 如果没有,我会把它留给 OP 来解决。
      • :) 实际上我忘记在发布之前将 lis 更改为名称 :)thanx 寻求帮助
      猜你喜欢
      • 1970-01-01
      • 2020-08-26
      • 1970-01-01
      • 1970-01-01
      • 2018-12-07
      • 1970-01-01
      • 2020-11-01
      • 2020-10-17
      • 1970-01-01
      相关资源
      最近更新 更多