How to delete only one row from a CSV file with python?

Question:

I’m trying to make a program which stores a list of names in a CSV file, and I’m trying to add a function to delete rows, which isn’t working as it deletes everything in the CSV file.

I’ve tried using writer.writerow(row), which hasn’t worked.

memberName = input("Please enter a member's name to be deleted.")
imp = open('mycsv.csv' , 'rb')
out = open('mycsv.csv' , 'wb')
writer = csv.writer(out)
for row in csv.reader(imp):
    if row == memberName:
        writer.writerow(row)
imp.close()
out.close()

I expected the program to only delete rows which contained memberName, but it deletes every row in the CSV file.

How do I change it to only delete a single row?

Asked By: Quento

||

Answers:

You can’t write to the same file while reading it. Instead, use another file for output, e.g.:

import csv

member_name = input("Please enter a member's name to be deleted: ")

with open('in_file.csv') as in_file, open('out_file.csv', 'w') as out_file:
    reader = csv.reader(in_file)
    writer = csv.writer(out_file)
    for row in reader:
        if member_name not in row:  # exclude a specific row
            writer.writerow(row)

Alternatively, you could store needed rows in memory and write them back to the input file after resetting the file pointer:

import csv

member_name = input("Please enter a member's name to be deleted: ")

with open('in_file.csv', 'r+') as in_file:
    reader = csv.reader(in_file)
    rows = [row for row in csv.reader(in_file) if member_name not in row]
    in_file.seek(0)
    in_file.truncate()
    writer = csv.writer(in_file)
    writer.writerows(rows)
Answered By: Eugene Yarmash

This worked for me: you could write the contents of the csv file to a list, then edit the list in python, then write the list back to the csv file.

lines = list()
memberName = input("Please enter a member's name to be deleted.")
with open('mycsv.csv', 'r') as readFile:
    reader = csv.reader(readFile)
    for row in reader:
        lines.append(row)
        for field in row:
            if field == memberName:
                lines.remove(row)

with open('mycsv.csv', 'w') as writeFile:
    writer = csv.writer(writeFile)
    writer.writerows(lines)

Answered By: Lemon
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.