【问题标题】:Create /Output a New Text file txt from a dictionary [duplicate]从字典中创建/输出一个新的文本文件 txt [重复]
【发布时间】:2017-07-22 12:46:18
【问题描述】:

如果我有示例字典,是否可以将其输出到新的或现有的 .txt 文件?

d = {'Jim':'233-5467', 'Bob':'643-7894', 'Anne':'478-4392', 'Jill':'952-4532'}

【问题讨论】:

    标签: python file dictionary text output


    【解决方案1】:

    不需要模块。

    myfile = open('test.txt','w')
    d = {'Jim':'233-5467', 'Bob':'643-7894', 'Anne':'478-4392', 'Jill':'952-4532'}
    myfile.writelines('{}:{} '.format(k,v) for k, v in d.items())
    myfile.close()
    

    “test.txt”的内容:

    吉尔:952-4532 鲍勃:643-7894 吉姆:233-5467 安妮:478-4392

    【讨论】:

      【解决方案2】:

      使用json模块:

      import json
      json.dump(d, open("file.json", "w"))
      

      或者像@ZdaR 建议的那样:

      with open("file.json", "w") as out_file:
          json.dump(d, out_file)
      

      【讨论】:

        【解决方案3】:

        你要转成json,json可以用txt格式表示dict

        import json
        json.dump({'Jim':'233-5467', 'Bob':'643-7894', 'Anne':'478-4392', 'Jill':'952-4532'}, open('yourfile.json', 'w'))
        

        【讨论】:

          猜你喜欢
          • 2018-03-12
          • 2021-07-21
          • 1970-01-01
          • 1970-01-01
          • 2021-05-10
          • 1970-01-01
          • 1970-01-01
          • 2016-04-11
          • 1970-01-01
          相关资源
          最近更新 更多