Overwriting row in same csv file using dictwriter

两盒软妹~` 提交于 2019-12-01 19:51:31

问题


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'})

回答1:


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.


来源:https://stackoverflow.com/questions/33968785/overwriting-row-in-same-csv-file-using-dictwriter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!