我是python的菜鸟,需要帮助。我制作了一个电话簿,可以在其中添加联系人。但是问题是,当我退出程序时,对列表的更改没有保存。我希望用户能够对列表进行永久更改。我看到过有关file = open(“ something”,'w')代码的帖子,可以做到这一点(我认为),但是我不知道在哪里插入此代码,我也不了解是什么。有人可以帮助我了解这是怎么回事。这是完整的代码:
name = ["ranga","hari"]
number = [9895497777,9]
book = {name[0]:number[0],name[1]:number[1]}
def search():
print("Contacts:")
for x in book:
print(x,':',book[x])
while 1:
count = 0
a = 0
ch1 = input("search: ")
try:
ch1 = int(ch1)
except ValueError:
while a < len(name):
result = name[a].find(ch1)
if result == -1:
a = a + 1
else:
print(name[a],number[a])
a = a + 1
count = count + 1
if count == 0:
print("Not available.Try again")
continue
else:
break
ch1 = str(ch1)
while a < len(number):
sumber = str(number[a])
result = sumber.find(ch1)
if result == -1:
a = a + 1
else:
print(name[a],number[a])
a = a + 1
count += 1
if count == 0:
print("Not available.try again")
continue
else:
break
def add():
print("What is the name of the contact you want to add?")
name1 = input()
name.append(name1)
while 1:
print("What is the number of this contact?")
number1 = input()
try:
number1 = int(number1)
except ValueError:
print("Please type a number..")
continue
number.append(number1)
book[name1] = number1
break
def remoe():
print("Reference:")
for x in book:
print(x,':',book[x])
while 1:
print("What is the name of the contact you want to remove?")
name2 = input()
if name2 in book:
increment = name.index(name2)
name.pop(increment)
number.pop(increment)
del book[name2]
break
else:
print("Not available.Please try again")
while 1:
print("Contacts:")
for x in book:
print(x, ':', book[x])
print("\nWhat do you want to do?\n1.Search for a person\n2.edit the phone book\n3.exit")
choice = input()
try:
choice = int(choice)
except ValueError:
print("Type 1,2 or 3")
continue
if choice == 1:
search()
elif choice == 2:
while 1:
print("Do you want to:\n1.Add a contact\n2.Remove a contact\n3.Go back to main menu")
ch2 = input()
if ch2 in['3']:
break
else:
try:
ch2 = int(ch2)
except ValueError:
print("Type 1 or 2..")
if ch2 == 1:
add()
elif ch2 == 2:
remoe()
elif choice == 3:
exit()
else:
print("Type 1,2 or 3")
感谢您的帮助。
答案 0 :(得分:1)
我听取了您的建议,并制作了一个新的文本文件,但是我仍然不知道该怎么做,但是在阅读了您的答案后,我终于明白了。
removelist = []
def search():
while 1:
search = str(input("Search: "))
if search not in["exit", "Exit"]:
with open('output.txt', 'r+') as f:
line = f.readline()
while line:
data = line.find(search)
if not data == -1:
print(line.rstrip('\n'))
line = f.readline()
else:
line = f.readline()
else:
break
f.close()
def add():
print("Type the name of the contact:")
name = input()
while 1:
print("Type the number of this contact:")
number = input()
try:
number = int(number)
except ValueError:
print("Please type a number")
continue
number = str(number)
with open('output.txt', 'a+') as f:
f.write('\n' + name +' ' + number)
break
def remoe(): #this is where the problem comes in
while 1:
remove = str(input("Remove: "))
with open('output.txt', 'r+') as f:
line = f.readline()
while line:
if not remove in["Remove", "remove"]:
removelist.clear()
data = line.find(remove)
if not data == -1:
removelist.append(line) #This saves all the lines coming from the search to a
print(removelist) #removelist which can be accessed when you type in remove
line = f.readline() #But the problem is that if there is a \n at the end of the
else: #string then the remove function does not work
line = f.readline()
else:
print(removelist)
with open('output.txt', 'r') as f:
d = f.readlines()
f.close()
with open('output.txt', 'w') as f:
for i in d:
if i not in removelist:
f.write(i)
f.truncate()
f.close()
break
while 1:
with open('output.txt', 'r') as f:
data = f.read()
print("Contacts:")
print(data)
print('''What do you want to do?
1.Search for a contact
2.Edit contacts
3.Exit''')
f.close()
choice = input()
if choice in["1"]:
search()
elif choice in["2"]:
while 1:
print('''What do you wanna do:
1.Add a contact
2.Remove a contact
3.Exit to main menu''')
ch1 = input()
if ch1 in["1"]:
add()
elif ch1 in["2"]:
remoe()
elif ch1 in["3"]:
break
else:
print("Please type 1,2 or 3")
elif choice in[3]:
print("Ok bye")
else:
print("Please type 1,2 or 3")
现在问题似乎是删除功能..如果我尝试删除结尾处带有\ n的行,则在opp时将不起作用。似乎有效。有人猜我在这里做什么? 还要感谢Mayank porwal的帮助
答案 1 :(得分:0)
当您选择add
联系人时,确实会将姓名和电话号码正确地添加到列表中。但是,就是这样。
重新运行程序时,由于代码的前2
行,该列表将被重新分配:
name = ["ranga","hari"]
number = [9895497777,9]
因此,您不会看到最后的更改。
这是您应该维护file
的地方,它不在代码的范围内,而不是列表的范围。
您可以像这样修改add
函数:
def add():
print("What is the name of the contact you want to add?")
name1 = input()
#name.append(name1)
# Just add the name1 variable's value to the file
with open('contacts_list.txt', 'a+') as f:
f.write(name1 + '\n')
while 1:
print("What is the number of this contact?")
number1 = input()
try:
number1 = int(number1)
except ValueError:
print("Please type a number..")
continue
#number.append(number1)
# Similarly, append the number1 variable's value to file again.
with open('contacts_list.txt', 'w+') as f:
f.write(number1)
#book[name1] = number1
with open('contacts_list.txt', 'r') as f:
print(f.read())
break
注意:您还需要更改其他功能search
和remove
以便从文件中进行读写。我刚刚向您介绍了事情的完成方式。您需要修改代码并使之正常工作。
让我知道是否有帮助。
答案 2 :(得分:0)
首先,您应该知道名称= [“ ranga”,“ hari”],数字= [9895497777,9]已在代码中,并且您无法更改这些值,在exit()之后,它们将重置为默认值。
在此问题中,您应该使用文件(例如.txt文件): 1.您必须在项目中创建一个.txt文件(例如Contacts.txt) 2.并在其中写入您的信息(例如,第一行:Kourosh +98938 ....) 3.在程序的第一步,您必须阅读Contact.txt并将其加载到列表或字典之类的结构中(例如
>>> with open('workfile') as f:
... read_data = f.read()
>>> f.closed
)
4。现在您可以编辑,添加,删除结构。 5,最后您可以在exit()之前在文件中写入结构 例如:
>>> with open('workfile') as f:
... f.write(s)
>>> f.closed