如何使用python从csv文件中删除特定行

时间:2020-08-05 16:26:12

标签: python csv

我正在开发一个程序,并试图实现以下功能。

  • 添加新学生
  • 根据ID删除学生

这是我的代码

from csv import writer
import csv

def add(file_name, list_of_elem):
    # Open file in append mode
    with open(file_name, 'a+', newline='') as write_obj:
        # Create a writer object from csv module
        csv_writer = writer(write_obj)
        # Add contents of list as last row in the csv file
        csv_writer.writerow(list_of_elem)

def remove():
    id = input("Enter ID : ")
    with open('students.csv', 'rb') as inp, open('students.csv', 'wb') as out:
        writer = csv.writer(out)
        for row in csv.reader(inp):
            if row[0] != id:
                writer.writerow(row)


# List of strings
row_contents = [11,'mayur','Java','Tokyo','Morning']
# Append a list as new line to an old csv file
add('students.csv', row_contents)
remove()

添加功能可以正常工作,但是当我尝试使用删除功能时,它会删除所有现有条目。任何人都可以帮助我。

2 个答案:

答案 0 :(得分:0)

首先,我将显示代码,然后在下面,我对更改进行一些评论。

from csv import writer
import csv

def add(file_name, list_of_elem):
    # Open file in append mode
    with open(file_name, 'a+', newline = '') as write_obj:
        # Create a writer object from csv module
        csv_writer = writer(write_obj)
        # Add contents of list as last row in the csv file
        csv_writer.writerow(list_of_elem)

def remove():
    idt = input("Enter ID : ")
    with open('students.csv', 'r') as inp:
        newrows = []
        data = csv.reader(inp)
        for row in data:
            if row[0] != idt:
                newrows.append(row)
    with open('students.csv', 'w') as out:
        csv_writer = writer(out)
        for row in newrows:
            csv_writer.writerow(row)

def display():
    with open('students.csv','r') as f:
        data = csv.reader(f)
        for row in data:
                print(row)

# List of strings
row_contents = [10,'mayur','Java','Tokyo','Morning']
add('students.csv', row_contents)
row_contents = [11,'mayur','Java','Tokyo','Morning']
add('students.csv', row_contents)
row_contents = [12,'mayur','Java','Tokyo','Morning']
add('students.csv', row_contents)
# Append a list as new line to an old csv file

display()
remove()
  1. 如果文件是CSV文件,则应使用text文件,而不是binary文件。
  2. 我将变量id的名称更改为ìdt,因为id是内置的,用于返回对象的标识,并且不是覆盖内置函数的好习惯。
  3. 要仅删除具有特定idt的行,应阅读所有文件,存储到var(列表)中,删除要删除的内容,然后保存结果。

答案 1 :(得分:0)

您应该使用临时文件,而不要同时打开并写入同一文件。签出此答案:https://stackoverflow.com/a/17646958/14039323