首页 > 解决方案 > Python CSV 文件 - 如何从 CSV 文件中删除数据?

问题描述

当我在 Python 中练习 CSV 文件的知识时遇到了问题。我写了一些函数,比如从 CSV 文件中读取,将新数据添加到现有的 CSV 文件中,现在我想添加允许用户从 CSV 文件中删除一些数据的函数。我添加新数据的功能如下所示:

def writein():
    with open('employee data.csv', 'a') as employeeData:
        writeby = csv.writer(employeeData, delimiter = ',')
        writeNEN = input('Enter the name of the new employee: \n')
        writeNESN = input('Enter the surname of the new employee: \n')
        writeNEP = input('Enter the position of the new employee: \n')
        writeNEBD = input('Enter the date of birth of the new employee: \n')
        writeby.writerow([writeNEN, writeNESN, writeNEP, writeNEBD])

现在我想做同样的功能,但不是添加我想删除现有数据。我试过这个:

def dataremove():
    with open('employee data.csv', 'r') as employeeData:
        removewith = csv.remover(employeeData, delimiter = ',')

但是 csv 模块中没有像“删除”或“删除”这样的属性。

我如何编写允许删除少量数据的函数?

标签: pythonpython-3.xcsv

解决方案


要删除一些行,您应该阅读所有文件,删除您不想要的行(filter例如,您可以在行列表上执行此操作),然后重写所有 csv 文件。
我建议您使用pandas库来执行此操作,这样做可能有点矫枉过正,但简化了很多此操作

import pandas as pd
def writein():
        df = pd.read_csv('employee data.csv')
        writeNEN = input('Enter the name of the new employee: \n')
        writeNESN = input('Enter the surname of the new employee: \n')
        writeNEP = input('Enter the position of the new employee: \n')
        writeNEBD = input('Enter the date of birth of the new employee: \n')
        df.append([writeNEN, writeNESN, writeNEP, writeNEBD])
        df.to_csv('employee data.csv', index=False)

def delete():
        df = pd.read_csv('employee data.csv')
        df = df[~df.name.str.startswith('N')] #keep the names that don't start with N
        df.to_csv('employee data.csv', index=False)

推荐阅读