我尝试使用词典创建数据库。我将字典转换成字符串,一旦我完成添加和删除它的东西,但是当我想保存字符串时,我希望键在彼此的新行上。
到目前为止,这是我的代码:
delete
保存到文件时,我想保存每个密钥及其信息,如下所示:
print('|-----Welcome to the Address Book-------|')
print('|----------------------------------------|')
print('|Please choice from the following:-------|')
print('|----------1: Find Contact------------|')
print('|----------2: Add Contact------------|')
print('|----------3: Delete Contact------------|')
print('|----------4: Quit Address Book----------|')
choice = [1, 2, 3, 4, 5]
document = open('addresses.txt', 'r+')
address = {}
for line in document:
if line.strip():
key, value = line.split(None, 1)
address[key] = value.split()
document.close()
open('addresses.txt', 'w')
while 1:
answer = 0
while answer not in choice:
try:
answer = int(input("Enter here: "))
except ValueError:
0
if answer == 1:
x = input('Enter his/her name: ')
if x in address:
print("This is their address: ", address[x])
else:
print('Contact does not exist!')
if answer == 2:
x = (input('Enter new contact: '))
x = x.replace(" ", "_")
if x in address:
while True:
z = str(input('Contact '+x+' with address: '+str(address[x]) + ' already existed, do you want to override?(Yes/No)'))
if z == 'yes':
b = input('Enter Address: ')
c = input('Enter postcode: ')
del address[x]
break
elif z == 'no':
break
else:
print('Please choose yes or no')
else:
b = input('Enter Address: ')
c = input('Enter postcode: ')
b = b.replace(" ", "_")
c = c.replace(" ", "_")
address[x] = b, c
if answer == 3:
z = input('Enter whom you would like to delete: ')
if z in address:
del address[z]
else:
print('Contact does not exist!')
if answer == 4:
a = "{}':(),[]"
ok = str(address)
for char in a:
ok = ok.replace(char, "")
document = open('addresses.txt', 'r+')
document.write(ok + '\n')
document.close()
break
但是它保存的方式如下:
>Bob address postcode
>Sam address postcode
答案 0 :(得分:0)
将文字写入文件时,请执行以下操作:
with open('/file/path', 'w') as f:
for k, v in d.items():
f.write(k + v + "\n")
这假设了一些事情:
'w'
切换为'a'
key
和value
项均为str
答案 1 :(得分:0)
我不喜欢使用'r+'
。当您想要从文件中读取时,您应open(filename, "r")
;当您想要读取文件时,open(filename, "w")
应该{。}}}。在我看来,它更容易,因为在使用'r+'
时,你必须考虑寻找的位置(你在编写/编辑某处时看到的闪烁光标)。
为此你需要像:
file=open(filename,"r+")
file.seek(0)
file.write("something" + "\n")
嗯,我并没有真正使用"r+"
方法,所以我不能再解释了。我建议您在文档中阅读更多相关信息。
答案 2 :(得分:0)
如果您在屏幕上打印str(address)
,您就会明白为什么会这样。 str
命令将所有内容(即键和值)转换为连续字符串,并将其存储在文档文件中。
相反,您应该逐个保存地址簿的项目,迭代所有人。
ok = ""
for person in address:
ok += person + " " + address[person] + "\n"
with open('addresses.txt', 'w') as file_out:
file_out.write(ok)