【发布时间】:2017-07-22 12:46:18
【问题描述】:
如果我有示例字典,是否可以将其输出到新的或现有的 .txt 文件?
d = {'Jim':'233-5467', 'Bob':'643-7894', 'Anne':'478-4392', 'Jill':'952-4532'}
【问题讨论】:
标签: python file dictionary text output
如果我有示例字典,是否可以将其输出到新的或现有的 .txt 文件?
d = {'Jim':'233-5467', 'Bob':'643-7894', 'Anne':'478-4392', 'Jill':'952-4532'}
【问题讨论】:
标签: python file dictionary text output
不需要模块。
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'))
【讨论】: