if I have a sample dictionary is it possible to output it to a new or existing .txt file?
d = {'Jim':'233-5467', 'Bob':'643-7894', 'Anne':'478-4392', 'Jill':'952-4532'}
Use json
module:
import json
json.dump(d, open("file.json", "w"))
Or as @ZdaR suggested:
with open("file.json", "w") as out_file:
json.dump(d, out_file)
No modules needed.
myfile = open('test.txt','w')
d = {'Jim':'233-5467', 'Bob':'643-7894', 'Anne':'478-4392', 'Jill':'952-4532'}
myfile.writelines('{}:{} '.format(k,v) for k, v in d.items())
myfile.close()
Content of 'test.txt' :
Jill:952-4532 Bob:643-7894 Jim:233-5467 Anne:478-4392
You have to convert it to json, json
can represent dict
in txt format.
import json
json.dump({'Jim':'233-5467', 'Bob':'643-7894', 'Anne':'478-4392', 'Jill':'952-4532'}, open('yourfile.json', 'w'))