简体   繁体   English

使用 Python 删除 CSV 文件中的行

[英]Deleting row in CSV file using Python

I want to delete a specific line that matches the argument and remove the line from the CSV file.我想删除与参数匹配的特定行并从 CSV 文件中删除该行。 I can't seems to find a solution.我似乎无法找到解决方案。

The sample CSV data are as follows:示例CSV数据如下:

Apple, 1.0, 1.0
Banana, 2.1, 2.1
Carrot, 3.2, 3.2

Let's say I only want to remove the banana row, is is possible?假设我只想移除香蕉排,这可能吗?

def delete_place(name):
    file = open('data/db.csv', 'r')
    reader = csv.reader(file)

    for row in reader:
        if name != row[0]:
            return 'Place not found.', 400
        else:
            # todo: delete line in csv
            return 'Place with name {} deleted.'.format(name), 200

You can read csv file into pandas dataframe and then apply selection/deletion operation.您可以将 csv 文件读入pandas dataframe ,然后应用选择/删除操作。 Later dump the modified dataframe into a csv file稍后将修改后的数据帧转储到 csv 文件中

import pandas as pd
df = pd.read_csv('data/db.csv')
df = df[df['1']!='Banana'] # I am assuming the csv file had no header, hence by default it used 1 as the header of first column
df.to_csv('data/db_modified.csv', header=False, index=False)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM