Click here to Skip to main content
15,884,751 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I'm doing a school assignment and I created a delete function to remove a row from a csv file.
But it doesn't match my user input and delete the specific row. It just clears the file once I have entered an ID. I'm not sure whats the right way to do it hope i could find some help here.

This is the function I created.
def d_avatar():
    filePath = "data.csv"
    with open(filePath)	as csvfile:
        reader = csv.DictReader(csvfile)
        
        filePath = "sample_write_data.csv"
        with open(filePath,'w',newline='') as csvfile:
            fieldnames = ['name','tribe','id','Air','Water','Earth','Fire']
            writer = csv.DictWriter(csvfile,fieldnames=fieldnames)
        
            print("Delete an avatar")
            deletion = input("Enter avatar id to delete: ")
            
        for row in reader:
            if deletion != row['id']:
                print("avatar ID is not found")
                deletion = input("Enter avatar id to delete: ") 
            
            else:
                if deletion == row['id' ]:
                    writer.writerow(row) ; 

                print("Avatar Record Deleted")


What I have tried:

I have tried to use the various ways to delete the data using the del and writerow but it all gives me the same outcome of clearing the file.
Posted
Updated 23-May-19 5:05am

1 solution

Your deletion logic needs changing. Try this:
Python
for row in reader:
    if deletion != row['id']:
        writer.writerow(row) ; # write all non-matching rows
    else:
        print("Avatar Record Deleted") # nothing to write
 
Share this answer
 
Comments
Maciej Los 23-May-19 11:51am    
5ed!
Richard MacCutchan 23-May-19 11:55am    
Thanks Maciej. I get the impression that =, ==, and != cause confusion to some newer devs.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900