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
3
  • 2
    Does this answer your question? Deleting rows with Python in a CSV file Commented Jan 21, 2020 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. Commented Jan 21, 2020 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 Commented Jan 21, 2020 at 14:06

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.