且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何根据用户输入从csv文件中删除特定行?

更新时间:2023-12-03 21:22:40

您的删除逻辑需要更改。试试这个:

   读者:
如果删除!= row [' id']:
writer.writerow(row); 写下所有不匹配的行
else
print 已删除头像记录 无需撰写


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.

Your deletion logic needs changing. Try this:
for row in reader:
    if deletion != row['id']:
        writer.writerow(row) ; # write all non-matching rows
    else:
        print("Avatar Record Deleted") # nothing to write