Home:ALL Converter>Write dictionary to text file with newline

Write dictionary to text file with newline

Ask Time:2020-05-19T23:25:30         Author:user3848207

Json Formatter

I have a python dictionary {'A': '1', 'B': '2', 'C': '3'}. I want to write this dictionary into a file. This is how I did it;

test_dict = {'A': '1', 'B': '2', 'C': '3'}
f = open("dict.txt", "w")
f.write(str(test_dict))
f.close()

However, what I want the text file is to look like this;

{
'A': '1', 
'B': '2', 
'C': '3',
}

How do I add the newline when writing to the text file? I am using python 3.7

Author:user3848207,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/61894745/write-dictionary-to-text-file-with-newline
Renan Machado :

The str() method for a dict return it as a single line print, so if you want to format your output, iterate over the dict and write in the file the way you want.\n\ntest_dict = {'A': '1', 'B': '2', 'C': '3'}\nf = open(\"dict.txt\", \"w\")\nf.write(\"{\\n\")\nfor k in test_dict.keys():\n f.write(\"'{}':'{}'\\n\".format(k, test_dict[k]))\nf.write(\"}\")\nf.close()\n",
2020-05-19T15:51:25
yy