Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overwriting row in same csv file using dictwriter

Tags:

python

csv

writer

I have names.csv

first_name,last_name
Baked,Beans
Lovely,Spam
John,Bang
Harry,Potter

I want to rename "John Ban" with "jason statham" in same file. I tried to use file.seek() but failed

import csv
with open('/home/tiwari/Desktop/names.csv', 'rw+') as csvfile:
    fieldnames = ['first_name', 'last_name']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    reader = csv.DictReader(csvfile)
    for line, row in enumerate(reader):
        rs = sys.getsizeof(row)
        if row['first_name'] == 'John':
            csvfile.seek(-rs)
            writer.writerow({'first_name': 'Jason', 'last_name': 'statham'})
like image 476
sujit tiwari Avatar asked Nov 28 '15 07:11

sujit tiwari


Video Answer


1 Answers

Your approach will not work unless the replacement string is exactly same length with the original string.

I suggest to read all rows, and replace them, and write it back.

import csv

with open('/home/tiwari/Desktop/names.csv', 'r+') as csvfile:
    reader = csv.DictReader(csvfile)

    rows = []
    for row in reader:
        if row['first_name'] == 'John':
            row['first_name'] = 'Jason'
            row['last_name'] = 'Statham'
        rows.append(row)

    csvfile.seek(0)  # back to begining of the file.
    fieldnames = ['first_name', 'last_name']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerows(rows)
    csvfile.truncate()  # In case of updated content is shorter.
like image 65
falsetru Avatar answered Oct 24 '22 20:10

falsetru