2017-03-02 90 views

回答

1

無需模塊。

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

+0

謝謝@Anil_M – Supernova

1

使用json模塊:

import json 
json.dump(d, open("file.json", "w")) 

或者爲@ZdaR建議:

with open("file.json", "w") as out_file: 
    json.dump(d, out_file) 
0

你必須把它轉換成JSON,json可以txt格式代表dict

import json 
json.dump({'Jim':'233-5467', 'Bob':'643-7894', 'Anne':'478-4392', 'Jill':'952-4532'}, open('yourfile.json', 'w'))