在 Python 中重写 CSV 文件会弄乱行索引



这是我目前的全部项目。原始 CSV 文件有 4 行,其中包含联系人姓名、电子邮件和电话信息。"列表"查看"和"添加"功能工作正常,直到我使用"删除"功能。为了删除所需的行,我将文件放在列表中,删除用户输入的行,然后将列表重写为CSV文件,格式似乎不错。

import csv
print("Contact Listn")
print(" list - Display all contactsn","view - View a contactn","add - Add a contactn", "del - Delete a contactn", "exit - Exit programn")
def main():
userCom = input("nCommand: ")
if userCom == "list":
lists()
elif userCom == "view":
count()
elif userCom == "add":
add()
elif userCom == "del":
delete()
elif userCom == "exit":
exitt()
else :
print("Invaild input, try again")
main()
def count():
counter = 1
with open("contacts.csv") as file:
number = file.readline()
for line in file:
counter = counter +1
view(counter)
def lists():        
with open("contacts.csv", newline="") as file:
reader = csv.reader(file)
counter = 0
for row in reader:
print(int(counter) + 1, ". ",row[0])
counter = counter+1
main()
def view(count):
num = input("Enter a contact's number to view their information: ")
while num.isdigit() == False or int(num) < 1 or int(num) > int(count):
print("Invaild input, try again")
view(count)
reader = csv.reader(open("contacts.csv"))
lines = list(reader)
print("Name: ",lines[int(num)-1][0],"nEmail: ",lines[int(num)-1][1],"nPhone Number: ",lines[int(num)-1][2])
main()
def add() :
name = input("Name: ")
email = input("Email: ")
phone = input("Phone: ")
added = [name,",",email,",",phone]
with open("contacts.csv", "a") as file:
for item in added:
file.write(item)
print(name, " was added.")
file.close()
main()
def delete():
deleted = input("Enter number to delete: ")
reader = csv.reader(open("contacts.csv"))
contacts = list(reader)
del contacts[int(deleted)-1]
with open("contacts.csv", "w") as file:
writer = csv.writer(file)
writer.writerows(contacts)
print("Number ",deleted," was deleted.")`enter code here`
file.close()
main()

main()

当我使用删除并尝试"列表"或"查看"功能时,我收到以下错误消息: 回溯(最近一次调用):

File "C:UsersTestDesktopcontacts_1.py", line 81, in <module>
main()
File "C:UsersTestDesktopcontacts_1.py", line 15, in main
delete()
File "C:UsersTestDesktopcontacts_1.py", line 72, in delete
main()
File "C:UsersTestDesktopcontacts_1.py", line 9, in main
lists()
File "C:UsersTestDesktopcontacts_1.py", line 35, in lists
print(int(counter) + 1, ". ",row[0])
IndexError: list index out of range

任何帮助都会有所帮助!

这是因为您的row不包含任何行,因此它甚至没有0索引。 在访问其中的任何项目之前,您必须检查列表是否包含某些内容:

if row:
print(row[0])

正如我在评论中所说,您的解决方案是有缺陷的,因为它会在某个时候溢出堆栈。您应该使用无限循环,而不是一次又一次地调用main函数

def main():
while 1:
userCom = input("nCommand: ")
if userCom == "list":
lists()
elif userCom == "view":
count()
elif userCom == "add":
add()
elif userCom == "del":
delete()
elif userCom == "exit":
exitt()
else:
print("Invaild input, try again")
# main()

最新更新