问题
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