如何根据用户输入从csv文件中删除特定行? [英] How do delete a specific row from a csv file based on a user input?

查看:955
本文介绍了如何根据用户输入从csv文件中删除特定行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个学校作业,我创建了一个删除函数来从csv文件中删除一行。

但是它与我的用户输入不匹配并删除了特定的行。它只是在我输入ID后清除文件。我不知道什么是正确的方法,希望我能在这里找到一些帮助。



这是我创建的功能。

 def d_avatar():
filePath =data.csv
with open(filePath)as csvfile:
reader = csv.DictReader(csvfile)

filePath =sample_write_data.csv
打开(filePath,'w',newline ='')为csvfile:
fieldnames = ['name','tribe','id ','Air','Water','Earth','Fire']
writer = csv.DictWriter(csvfile,fieldnames = fieldnames)

print(删除头像)
删除=输入(输入要删除的头像ID:)

用于读取行:
如果删除!= row ['id']:
print (找不到头像ID)
删除=输入(输入要删除的头像ID:)

else:
i f deletion == row ['id']:
writer.writerow(row);

打印(阿凡达记录已删除)





我尝试过:



我试图用各种方法使用del和writerow删除数据但是这一切都给了我清除文件的相同结果。

解决方案

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

   读者:
如果删除!= 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


这篇关于如何根据用户输入从csv文件中删除特定行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆