Rewriting a line in the same csv file using a voice recorder

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 the same file. I tried using 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'}) 
+5
source share
1 answer

Your approach will not work unless the replacement string is exactly the same length as the original string.

I suggest reading all the lines and replacing them and writing them 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. 
+3
source

Source: https://habr.com/ru/post/1236994/


All Articles