我有一个程序来制作一个地址簿,我希望能够在这样做之前确认对记录的更改 - 如果我搜索姓氏“Peterson”并且有两个条目,我可以选择更改一个,两者,或两者都没有 . 我正在尝试使用基本相同的代码来编辑现有行,或者从程序中删除它 . 我是Python的新手,这是我上课的最后一个项目,我花了四天的时间试图找出哪些不起作用 . 我一直在浏览Stack Overflow并且没有找到一个令人满意的答案我的问题,我确信这是因为我不太了解Python . 我们应该使用创建和重命名临时文件的设置,所以虽然我知道这不是最有效的,但这是我应该做的 .
这就是我所拥有的:
import os
FIRSTNAME = 0
LASTNAME = 1
STREETADDRESS = 2
CITY = 3
STATE = 4
ZIP = 5
TELEPHONE1 = 6
TELEPHONE2 = 7
def modify():
found = False
search = input("Enter an item to search for: ")
new = input("And what should we change it to? ")
addressbook = open("addressbook.txt", "r")
temp_file = open("temp.txt", "w")
line = addressbook.readline()
while line != "":
line = line.rstrip("\n")
lineInfo = line.split("|")
if lineInfo[1] == search:
print("I found it!")
print(format(lineInfo[FIRSTNAME], '15s'),format(lineInfo[LASTNAME], '15s'),format(lineInfo[STREETADDRESS], '20s'),format(lineInfo[CITY], '10s'),
format(lineInfo[STATE], '5s'),format(lineInfo[ZIP], '10s'),format(lineInfo[TELEPHONE1], '15s')," ",format(lineInfo[TELEPHONE2], '10s'))
print()
delete = input("change this one? press y for yes.")
if delete == "y":
found = True
lineInfo[1] = new
temp_file.write(format(lineInfo[FIRSTNAME])+"|")
temp_file.write(format(lineInfo[LASTNAME])+"|")
temp_file.write(format(lineInfo[STREETADDRESS])+"|")
temp_file.write(format(lineInfo[CITY])+"|")
temp_file.write(format(lineInfo[STATE])+"|")
temp_file.write(format(lineInfo[ZIP])+"|")
temp_file.write(format(lineInfo[TELEPHONE1])+"|")
temp_file.write(format(lineInfo[TELEPHONE2])+"|")
temp_file.write("\n")
else:
temp_file.write(line)
temp_file.write("\n")
else:
temp_file.write(line)
temp_file.write("\n")
line = addressbook.readline()
temp_file.close()
os.rename("temp.txt","newaddress.txt")
if found:
print("File has been changed")
else:
print("File was not found")
modify()
现在,当我运行它时,我得到了这个:
Enter an item to search for: Peterson
And what should we change it to? Patterson
I found it!
Edward Peterson 10 Grand Pl
Kearny NJ 90031 383-313-3003 xxx
change this one? press y for yes.n
I found it!
James Peterson 11 Grand Pl
Kearny NJ 90021 xxx xxx
change this one? press y for yes.y
Traceback (most recent call last):
File "C:\Users\kendr\Desktop\Address Book\Delete Address Book.py", line 53, in <module>
delete()
File "C:\Users\kendr\Desktop\Address Book\Delete Address Book.py", line 22, in delete
if lineInfo[1] == search:
IndexError: list index out of range
老实说,我完成了这项任务,所以任何和所有的帮助都会产生巨大的影响 . 谢谢,K
1 回答
在检查线是否为空之前,您需要移动
line = line.rstrip("\n")
:否则你会在最后一行读到
"\n"
,这将使测试失败,所以你将进入循环体并尝试读取处理这个空行 .