[英]Python CSV file - How to remove data from CSV file?
當我在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 modul中沒有像“刪除”或“刪除”這樣的屬性。
如何編寫允許刪除少量數據的功能?
通常,沒有從計算機文件中“刪除”數據的事情。 您只能刪除整個文件,截斷文件以從末尾刪除一些內容,或者讀取舊內容,在內存中進行編輯並將其寫入新文件。
執行所需操作的最簡單方法是使用csv.reader
加載數據,根據需要進行編輯,然后像現在一樣使用csv.writer
。
要刪除一些行,您應該閱讀所有文件,刪除不需要的行(例如,可以使用filter
在行列表中執行此操作),然后重寫所有csv文件。
我建議您使用pandas
庫來執行此操作,也許這樣做有些矯but過正,但簡化了此操作
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.