1

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?

0

2 Answers 2

4

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

Comments

2

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)

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.