import csv input_file = "../data/passengers.csv" output_file = "../data/passengers2.csv" with open(input_file, 'r') as csv_input: with open(output_file, 'w', newline='') as csv_output: reader = csv.reader(csv_input) writer = csv.writer(csv_output) # Iterate through each row in the CSV for row in reader: # Get the last field in the row location = row[-1] # Split the location into two parts if it contains '/' and ',' if '/' in location and ',' in location: location1, location2 = location.split('/') # Further split location1 into city1 and country1 city1, country_state1 = location1.split(',', 1) # Further split location2 into city2 and country2 city2, country_state2 = location2.split(',', 1) elif ',' in location: city1, country_state1 = location.split(',', 1) # For the second location, set to empty strings city2, country_state2 = "", "" else: # If no city and country details are present city1, country_state1, city2, country_state2 = "", "", "", "" # Now replace the last field with the 4 new fields row[-1:] = [city1.strip(), country_state1.strip(), city2.strip(), country_state2.strip()] # Write the row into the new csv file writer.writerow(row)