Writing a dictionary to a text file?

前端 未结 10 747
挽巷
挽巷 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 04:14

    I know this is an old question but I also thought to share a solution that doesn't involve json. I don't personally quite like json because it doesn't allow to easily append data. If your starting point is a dictionary, you could first convert it to a dataframe and then append it to your txt file:

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

    I hope this could help.

    0 讨论(0)
  • 2020-11-28 04:16

    For list comprehension lovers, this will write all the key : value pairs in new lines in 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 ]
    
    0 讨论(0)
  • 2020-11-28 04:18

    I do it like this in python 3:

    with open('myfile.txt', 'w') as f:
        print(mydictionary, file=f)
    
    0 讨论(0)
  • 2020-11-28 04:21

    You can do as follow :

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

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

    0 讨论(0)
提交回复
热议问题