使用dictwriter覆盖相同csv文件中的行

时间:2015-11-28 07:17:16

标签: python csv writer

我有names.csv

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

我想重命名" John Ban"与" jason statham"在同一个文件中。 我试图使用file.seek()但是失败了

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 个答案:

答案 0 :(得分:3)

除非替换字符串与原始字符串的长度完全相同,否则您的方法将无效。

我建议读取所有行,然后替换它们,并将其写回。

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.