TmX GordioN REKT
TmX GordioN REKT

Reputation: 95

Delete a row from csv file

name = input("Enter a name : ")
fieldnames = ["first_name", "number"]
with open('names.csv') as csvfile, open('output.csv', 'w') as outputfile:
    reader = csv.DictReader(csvfile, fieldnames=fieldnames)
    writer = csv.DictWriter(outputfile, fieldnames=fieldnames)
    for line in reader:
        if name not in line:
            fieldnames = ["name", "number"]
            writer.writeheader()
            writer.writerow({'first_name': row['first_name'],
                             'number': row['number']})
with open('names.csv', 'w') as csvfile, open('output.csv') as outputfile:
    reader = csv.DictReader(outputfile, fieldnames=fieldnames)
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    for row in reader:
        fieldnames = ['first_name', 'number']
        writer.writeheader()
        writer.writerow({'first_name': row['first_name'],
                         'last_name': row['number']})

This is what I've coded so far. I want to write the rows which doesn't include name variable in it to the output file and write it back to the csvfile (names.csv)

James Smith,2025550131
Kevin Harris,2025550105

This is how my csvfile looks like.

first_name,last_name
James Smith,2025550131
first_name,last_name
James Smith,2025550131

This is the names.csv file after I run the code.

Upvotes: 1

Views: 5255

Answers (2)

Jean-François Fabre
Jean-François Fabre

Reputation: 140287

row isn't declared in your first write loop, so running this in an IDE could have memorized the output of a semi-successful attempt and you have a weird issue.

You also write the header each time. Just don't, it's done by default.

Also: you're comparing to the keys, not to the values. if name not in row: checks if the name is a key, which cannot happen, keys are "first_name", and "number".

You need to do if name != row['first_name']:

Last but not least, no need to read/write the file again to replace the input, just perform a shutil.move to overwrite with the output.

My fix proposal (note newline='', better when using python 3 to avoid blank lines on some not so up-to-date versions):

import shutil,csv

name = input("Enter a name : ")
fieldnames = ["first_name", "number"]
with open('names.csv') as csvfile, open('output.csv', 'w',newline='') as outputfile:
    reader = csv.DictReader(csvfile, fieldnames=fieldnames)
    writer = csv.DictWriter(outputfile, fieldnames=fieldnames)
    for row in reader:   # row, not line !!
        if name != row['first_name']:
            writer.writerow({'first_name': row['first_name'], 'number': row['number']})

# replace original file
shutil.move('output.csv','names.csv')

Upvotes: 3

Vikash Singh
Vikash Singh

Reputation: 14021

You need to read the input name.csv file.

Check in name matches the input name, then ignore that row.

If it does not match then write the content to output file.

In the end just copy the output file over the original name.csv file.

import csv, shutil
name = 'vikash' # This you can take as input from user
fieldnames = ["first_name", "number"]
with open('names.csv', 'r') as csvfile, open('output.csv', 'w') as outputfile:
    reader = csv.DictReader(csvfile, fieldnames=fieldnames)
    writer = csv.DictWriter(outputfile, fieldnames=fieldnames)
    for row in reader:
        if not name == row['first_name']:
            writer.writerow({'first_name': row['first_name'], 'number': row['number']})
shutil.move('output.csv','names.csv')

names.csv

first_name,number
vikash,1
viki,2
pawan,3

output.csv

first_name,number
viki,2
pawan,3

The reason why your code didn't work:

name = input("Enter a name : ")
fieldnames = ["first_name", "number"]
with open('names.csv') as csvfile, open('output.csv', 'w') as outputfile:
    reader = csv.DictReader(csvfile, fieldnames=fieldnames)
    writer = csv.DictWriter(outputfile, fieldnames=fieldnames)
    for line in reader:
        # you are reading line from reader but you are using row later.
        if name not in line:
            fieldnames = ["name", "number"]
            # above line is not needed as its already initialised earlier.
            writer.writeheader()
            # this is not required as header will be written automatically. 
            # Plus you also don't want to write header ever time you write a row to the output file.
            writer.writerow({'first_name': row['first_name'], 'number': row['number']})
            # use line variable here or change line above to row.

Upvotes: 0

Related Questions