使用 dictwriter 覆盖同一 csv 文件中的行
Overwriting row in same csv file using dictwriter
我有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'})
除非替换字符串的长度与原始字符串的长度完全相同,否则您的方法将不起作用。
我建议读取所有行,替换它们,然后写回。
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.
我有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'})
除非替换字符串的长度与原始字符串的长度完全相同,否则您的方法将不起作用。
我建议读取所有行,替换它们,然后写回。
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.