代码之家  ›  专栏  ›  技术社区  ›  TryingToGain

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

  •  1
  • TryingToGain  · 技术社区  · 7 年前

    这是我目前的整个项目。原始CSV文件有4行,其中包含联系人姓名、电子邮件和电话信息。在我使用“delete”函数之前,“list”、“view”和“add”函数都可以正常工作。为了删除所需的行,我将文件放在一个列表中,删除了用户输入的行,并将列表重新写入CSV文件中,格式看起来不错。

    import csv
    
    print("Contact List\n")
    print(" list - Display all contacts\n","view - View a contact\n","add - Add a contact\n", "del - Delete a contact\n", "exit - Exit program\n")
    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()
    

    当我使用delete并尝试“list”或“view”功能时,会收到以下错误消息: 回溯(最近一次呼叫最后一次):

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

    任何帮助都有帮助!

    1 回复  |  直到 7 年前
        1
  •  0
  •   Denis    7 年前

    这是因为 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()