Reputation: 4917
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
Upvotes: 2
Views: 9185
Reputation: 28030
This method uses F-string which results in more readable code. F-string is supported in python v3, not v2
f = open("dict.txt", "w")
f.write("{\n")
for k in test_dict.keys():
f.write(F"'{k}': '{test_dict[k]}',\n") # add comma at end of line
f.write("}")
f.close()
Upvotes: 0
Reputation: 76
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.
test_dict = {'A': '1', 'B': '2', 'C': '3'}
f = open("dict.txt", "w")
f.write("{\n")
for k in test_dict.keys():
f.write("'{}':'{}'\n".format(k, test_dict[k]))
f.write("}")
f.close()
Upvotes: 6