I have a csv file with four columns and about 26K rows. There are addresses in the fourth column and some of them have the country name at the end. I want to take the country string out of the file.
The current code I have is:
import csv
with open('file.csv', 'rt') as rf:
reader = csv.reader(rf, delimiter=',')
for row in reader:
#print(row[3]) # this works
usa = "United States"
if usa in row[3]:
#print("Its here!)") #this works too
repl = row[3].replace("United States", " " )
# need to write to file- find out how to write changes to a csv file
with open('file.csv', 'w') as wf:
writer = csv.writer(wf)
writer.writerows(repl)
rf.close()
wf.close()
If you didn't already guess, it just deletes everything in the entire file.
My approach is obviously very wrong.
Do I pull each line into memory, check, replace where necessary, and re-write?
What is the best way to iterate through a CSV file (only editing a specific column, but searching all rows for that column?
Thanks!
Edit: This was marked as a duplicate, but my question is not how to replace a single value in a csv file- it is a question about how to find & replace a multitude of values, and what the appropriate algorithm looks like for traversing csv files. I have not found any existing SO questions that adequately address this.
Edit #2: As requested, the snippet looks like:
First Name,, Last Name,, ID,, Address