1

I want to delete a specific line that matches the argument and remove the line from the CSV file. I can't seems to find a solution.

The sample CSV data are as follows:

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
Hadif Hatta
  • 75
  • 1
  • 11
  • 2
    Does this answer your question? [Deleting rows with Python in a CSV file](https://stackoverflow.com/questions/29725932/deleting-rows-with-python-in-a-csv-file) – Muhammad Hassan Jan 21 '20 at 14:03
  • There is no way to delete the line, but to choose to omit the line when going through the entire file. So, read file line by line until you found the line you don't want, skip it and continue. – thuyein Jan 21 '20 at 14:05
  • Note that the checks are case sensitive so you would need to use "Banana" when calling the function. On Linux you could just use grep: `grep -v Banana file.csv > new_file.csv` – Ionut Ticus Jan 21 '20 at 14:06

1 Answers1

0

You can read csv file into pandas dataframe and then apply selection/deletion operation. Later dump the modified dataframe into a csv file

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)
Shrey
  • 1,242
  • 1
  • 13
  • 27