如何使用python删除CSV中的仅一行 [英] How to delete only one row in CSV with python

查看:74
本文介绍了如何使用python删除CSV中的仅一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个程序来在CSV文件中存储名称列表,并且试图添加一个删除行的功能,该功能无法正常工作,因为它删除了CSV文件中的所有内容.

I'm trying to make a program which stores a list of names in a CSV file, and I'm trying to add a function to delete rows, which isn't working as it deletes everything in the CSV file.

我尝试使用writer.writerow(row),但该方法无效.

I've tried using writer.writerow(row), which hasn't worked.

        memberName = input("Please enter a member's name to be deleted.")
        imp = open('mycsv.csv' , 'rb')
        out = open('mycsv.csv' , 'wb')
        writer = csv.writer(out)
        for row in csv.reader(imp):
            if row == memberName:
                writer.writerow(row)
        imp.close()
        out.close()

我希望程序仅删除包含memberName的行,但是它将删除CSV文件中的每一行.如何将其更改为仅删除一行?

I expected the program to only delete rows which contained memberName, but it deletes every row in the CSV file. How do I change it to only delete a single row?

推荐答案

这对我有用:您可以将csv文件的内容写入列表,然后在python中编辑列表,然后将列表写回到csv文件.

This worked for me: you could write the contents of the csv file to a list, then edit the list in python, then write the list back to the csv file.

lines = list()
memberName = input("Please enter a member's name to be deleted.")
with open('mycsv.csv', 'r') as readFile:
    reader = csv.reader(readFile)
    for row in reader:
        lines.append(row)
        for field in row:
            if field == memberName:
                lines.remove(row)

with open('mycsv.csv', 'w') as writeFile:
    writer = csv.writer(writeFile)
    writer.writerows(lines)

这篇关于如何使用python删除CSV中的仅一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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