我必须创建一个保存功能和一个加载函数,它以以下格式保存字典:
123;Kalle;
123;Maria;
321;Anna;
321;Olle;
我的字典应该看起来像电话簿,键是名称,值是phonenumber:
telebook = {"jacob":"8472923777", "nisse":"092563243"}
如何编写以上述格式保存电话簿的功能?它应该是这样的:
8472923777;jacob;
这是我目前的代码:
def save(lista, telebook):
import pickle
filename = lista[1]
f = open(filename, "w")
pickle.dump(telebook, f)
f.close()
print telebook
def load(lista, telebook):
import pickle
try:
filename = lista[1]
f = open(filename, "r")
telebook_1 = pickle.load( f )
telebook.clear()
telebook.update(telebook_1)
f.close()
print telebook
except:
print "This file doesn't exist"
编辑:
我的保存功能比我想象的要容易,设法自己解决。不知道如何使加载功能工作。
book = raw_input("telebook> ").lower()
lista = book.split()
def save(lista, telebook):
filename = lista[1]
f = open(filename, "w")
for name, num in telebook.items():
f.write(num+";"+name+";"+"\n")
f.close()
print telebook
我的负荷和以前一样,但显然我不能再使用那个了。
答案 0 :(得分:0)
<h1>Main title</h1>
<p>Main text</p>
<div class="container">
<h1>Title</h1>
<p>Text</p>
</div>
并将其取回:
def save(telebok, filepath):
with open(filepath, 'w') as outfile:
for name,num in telebok.items():
outfile.write("{};{};\n".format(num, name))