Writing a dictionary to a text file?

前端 未结 10 746
挽巷
挽巷 2020-11-28 03:16

I have a dictionary and am trying to write it to a file.

exDict = {1:1, 2:2, 3:3}
with open(\'file.txt\', \'r\') as file:
    file.write(exDict)
相关标签:
10条回答
  • 2020-11-28 03:58
    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()
    
    0 讨论(0)
  • 2020-11-28 04:00

    If you want a dictionary you can import from a file by name, and also that adds entries that are nicely sorted, and contains strings you want to preserve, you can try this:

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

    Then to import:

    from file import dictionary_name
    
    0 讨论(0)
  • 2020-11-28 04:03
    import json
    
    with open('tokenler.json', 'w') as file:
         file.write(json.dumps(mydict, ensure_ascii=False))
    
    0 讨论(0)
  • 2020-11-28 04:06

    First of all you are opening file in read mode and trying to write into it. Consult - IO modes python

    Secondly, you can only write a string to a file. If you want to write a dictionary object, you either need to convert it into string or serialize it.

    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
    

    In case of serialization

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

    For python 3.x pickle package import would be different

    import _pickle as pickle
    
    0 讨论(0)
  • 2020-11-28 04:07

    The probelm with your first code block was that you were opening the file as 'r' even though you wanted to write to it using 'w'

    with open('/Users/your/path/foo','w') as data:
        data.write(str(dictionary))
    
    0 讨论(0)
  • 2020-11-28 04:07
    exDict = {1:1, 2:2, 3:3}
    with open('file.txt', 'w+') as file:
        file.write(str(exDict))
    
    0 讨论(0)
提交回复
热议问题