如果我有一個示例字典,是否可以將其輸出到新的或現有的.txt文件?從字典中創建/輸出新的文本文件txt
d = {'Jim':'233-5467', 'Bob':'643-7894', 'Anne':'478-4392', 'Jill':'952-4532'}
如果我有一個示例字典,是否可以將其輸出到新的或現有的.txt文件?從字典中創建/輸出新的文本文件txt
d = {'Jim':'233-5467', 'Bob':'643-7894', 'Anne':'478-4392', 'Jill':'952-4532'}
無需模塊。
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()
'的test.txt' 的內容:
吉爾:952-4532鮑勃:643-7894吉姆:233-5467安妮:478-4392
使用json
模塊:
import json
json.dump(d, open("file.json", "w"))
或者爲@ZdaR建議:
with open("file.json", "w") as out_file:
json.dump(d, out_file)
你必須把它轉換成JSON,json
可以txt格式代表dict
。
import json
json.dump({'Jim':'233-5467', 'Bob':'643-7894', 'Anne':'478-4392', 'Jill':'952-4532'}, open('yourfile.json', 'w'))
謝謝@Anil_M – Supernova