我有names.csv
first_name,last_name
Baked,Beans
Lovely,Spam
John,Bang
Harry,Potter
我想在同一个文件中用“jason statham”重命名“John Ban”.
我试图使用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'})
最佳答案
除非替换字符串与原始字符串的长度完全相同,否则您的方法将无效.
我建议读取所有行,并替换它们,并将其写回.
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',fieldnames=fieldnames)
writer.writeheader()
writer.writerows(rows)
csvfile.truncate() # In case of updated content is shorter.