Rewriting CSV file in Python messes up index of rows

时间:2018-03-23 00:13:04

标签: python list csv range

This is my entire project at the moment. The original CSV file has 4 rows with a contacts name, email, and phone information. The "list" "view" and "add" functions work fine until I use the "delete" function. In order to delete the desired line, I put the file in a list, deleted the row the user inputs, and rewrote the list into the CSV file with what appears to be good format.

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()

When I use delete and try the "list" or "view" features, I get this error message: Traceback (most recent call last):

  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

Any help helps!

1 个答案:

答案 0 :(得分:0)

This is because your row doesnt contain any line, so it doesn't even have the 0 index. Yo must check if the list contain something before accessing any item inside:

if row:
    print(row[0])

As I said in comment, your solution is flawed, because it will overflow the stack at some point. You should use an infinite loop instead of calling the main function again and again

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()