python - 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 模块中没有像“删除”或“删除”这样的属性。
我如何编写允许删除少量数据的函数?
解决方案
要删除一些行,您应该阅读所有文件,删除您不想要的行(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)
推荐阅读
- c# - 字符串长度超过 maxJsonLength 属性
- mobile - 颤动 - 如何在颤动中保存状态选择的单选按钮列表?
- javascript - 如何在 javascript 中使用 Loop 复制 HTML 元素
- mysql - Spring Boot + JPA [Hibernate backed] + mysql = 数据截断:第 1 行的列“ATTRIBUTE_NAME”的数据太长
- amazon-web-services - 如何解决从 Amazon lex 获得的 424 (Failed Dependency) (python)?
- rpa - 通过 Automation Anywhere 访问 500 次后,SAP 运行速度变慢
- php - MySQL:当日期计数超过给定数量时选择日期范围内的数据
- linkedin - LinkedIn Api 从所有者错误中获取帖子/共享
- python - 一个可以收发消息的mqtt客户端如何实现多线程
- c# - 在 C# 中使用具有 websocket 端点的 api