I have a CSV file as following:
fruit, country, city
banana, japan, tokyo
apple, brazil, rio
apple, korea, south, seoul
banana, denmark, copenhagen
This is an example, in reality, I have this issue in multiple large files. The issue being I can not read the 4th row with a comma delimiter as it will have one column too much.
My idea is to
- open the file with csv.reader
- find rows with term1 in column 2 and term2 in column 3 (in my example, term1=korea and term2=south)
- Replace term1 in column 2 with term1 and term2 combined (korea south) and deleted the 3rd column in the row
- save the edited file
In the code below I have completed the first two steps, but I am stuck on step 3 and 4.
import csv
path = r'C:\Users\jlobo\Desktop\example.txt'
with open(path, newline='') as csvfile:
csv_read = csv.reader(csvfile, delimiter=',', quotechar='"') #
for row in csv_read:
search_terms1 = ["korea"]
search_terms2 = ["south"]
if any([term in row[1] for term in search_terms1]) and any([term in row[2] for term in search_terms2]):
print(row)
How can I do steps 3 and 4? Or if relevant is there an alternative solution to the problem?