【问题标题】:Writing a dictionary to a text file?将字典写入文本文件?
【发布时间】:2016-08-26 05:14:54
【问题描述】:

我有一本字典,正在尝试将其写入文件。

exDict = {1:1, 2:2, 3:3}
with open('file.txt', 'r') as file:
    file.write(exDict)

然后我有错误

file.write(exDict)
TypeError: must be str, not dict

所以我修复了这个错误,但又出现了另一个错误

exDict = {111:111, 222:222}
with open('file.txt', 'r') as file:
    file.write(str(exDict))

错误:

file.write(str(exDict))
io.UnsupportedOperation: not writable

我不知道该怎么做,因为我还是 python 的初学者。 如果有人知道如何解决问题,请提供答案。

注意:我使用的是 python 3,而不是 python 2

【问题讨论】:

    标签: python-3.x file dictionary file-writing


    【解决方案1】:

    首先,您以读取模式打开文件并尝试写入。 咨询-IO modes python

    其次,您只能将字符串写入文件。如果要写字典对象,要么转成字符串,要么序列化。

    import json
    
    # as requested in comment
    exDict = {'exDict': exDict}
    
    with open('file.txt', 'w') as file:
         file.write(json.dumps(exDict)) # use `json.loads` to do the reverse
    

    在序列化的情况下

    import cPickle as pickle
    
    with open('file.txt', 'w') as file:
         file.write(pickle.dumps(exDict)) # use `pickle.loads` to do the reverse
    

    对于 python 3.x pickle 包导入会有所不同

    import _pickle as pickle
    

    【讨论】:

    • 成功了!虽然,它只写字典的内容。你能把它写成:exDict = {111:111, 222:222}
    • 我想到了这一点,但认为有更好的方法。它虽然有效,但谢谢!
    • 如果您不太喜欢= 符号,我所做的编辑可能会完成这项工作。
    • 你以前的方式:file.write('exDict = ' + json.dumps(exDict)) 对我来说很好,因为我现在正在使用它。
    • @JanKukacka JSON 是一种标准数据格式。 str(exDict) 将产生的并不总是有效的 JSON。我脑后的一个原因是单引号在 JSON 文件中无效,而当我们使用 str 方法时可能会出现。
    【解决方案2】:
    fout = "/your/outfile/here.txt"
    fo = open(fout, "w")
    
    for k, v in yourDictionary.items():
        fo.write(str(k) + ' >>> '+ str(v) + '\n\n')
    
    fo.close()
    

    【讨论】:

    【解决方案3】:

    您的第一个代码块的问题是,即使您想使用 'w' 写入文件,您仍以“r”形式打开文件

    with open('/Users/your/path/foo','w') as data:
        data.write(str(dictionary))
    

    【讨论】:

    • 这是正确答案,因为问题中的代码有错误。
    • 当我尝试 json 路由时,我失败了,因为我在浮点数中有一些“NaN”值。如果您想编写 JSON,则无法在不损坏数据本身的情况下进行修复。因此,这个答案是首选,因为它可以保存文本文件以准确反映字典。
    【解决方案4】:

    我知道这是一个老问题,但我也想分享一个不涉及 json 的解决方案。我个人不太喜欢 json,因为它不允许轻松附加数据。 如果您的起点是字典,您可以先将其转换为数据框,然后将其附加到您的 txt 文件中:

    import pandas as pd
    one_line_dict = exDict = {1:1, 2:2, 3:3}
    df = pd.DataFrame.from_dict([one_line_dict])
    df.to_csv('file.txt', header=False, index=True, mode='a')
    

    我希望这会有所帮助。

    【讨论】:

    • 为什么要使用外部库来完成简单的任务? Python Simple 原则更好。
    • 不是很有用,因为我使用的大多数字典都不够简单,无法成为有用的 DataFrame 对象。
    【解决方案5】:

    你可以这样做:

    import json
    exDict = {1:1, 2:2, 3:3}
    file.write(json.dumps(exDict))
    

    https://developer.rhino3d.com/guides/rhinopython/python-xml-json/

    【讨论】:

      【解决方案6】:

      如果你想要一个字典,你可以按名称从文件中导入,并且添加排序良好的条目,并包含你想要保留的字符串,你可以试试这个:

      data = {'A': 'a', 'B': 'b', }
      
      with open('file.py','w') as file:
          file.write("dictionary_name = { \n")
          for k in sorted (data.keys()):
              file.write("'%s':'%s', \n" % (k, data[k]))
          file.write("}")
      

      然后导入:

      from file import dictionary_name
      

      【讨论】:

      • 这仅适用于字符串,不适用于字典中的其他类型。
      【解决方案7】:

      我在 python 3 中这样做:

      with open('myfile.txt', 'w') as f:
          print(mydictionary, file=f)
      

      【讨论】:

      • 我喜欢这个,因为不需要导入。 data.write(str(dictionary)) 上面的答案将不适用于正确的字典,因为它只会在您的文件中写入
      • 我也很好奇的一件事是为什么不只做 print(mydictionary, file=open('myfile.txt', 'w'))
      • @MadmanLee 我认为两者都可以,这取决于我们更喜欢代码的样子。
      • with open('myfile.txt', 'r') as f: content = f.read(); dic = eval(内容);
      • json 比仅仅将str(mydict) 写入文件更好的原因恰恰是你不需要eval 的内容来获取dict 对象。 eval 是一个安全 rosk,如果有更好的选择,则不应使用。
      【解决方案8】:
      import json
      
      with open('tokenler.json', 'w') as file:
           file.write(json.dumps(mydict, ensure_ascii=False))
      

      【讨论】:

      • 您可以通过添加解释其工作原理来改进此错误。
      【解决方案9】:

      对于列表理解爱好者,这会将所有key : value 对写入dog.txt 的新行中

      my_dict = {'foo': [1,2], 'bar':[3,4]}
      
      # create list of strings
      list_of_strings = [ f'{key} : {my_dict[key]}' for key in my_dict ]
      
      # write string one by one adding newline
      with open('dog.txt', 'w') as my_file:
          [ my_file.write(f'{st}\n') for st in list_of_strings ]
      

      【讨论】:

        【解决方案10】:
        exDict = {1:1, 2:2, 3:3}
        with open('file.txt', 'w+') as file:
            file.write(str(exDict))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多