gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
Write me a python 3 script that splits data into 2 csv files based on whether they have…
- User
Write me a python 3 script that splits data into 2 csv files based on whether they have key terms in that row
- Assistant
Certainly! Here's an example of a Python 3 script that reads a CSV file, checks each row for key terms, and splits the data into two separate CSV files based on whether they contain those key terms:
import csv def split_csv(input_file, output_file1, output_file2, key_terms): with open(input_file, 'r') as csv_file: reader = csv.reader(csv_file) header = next(reader) # Get the header row # Find the indices of the key terms in the header row key_term_indices = [header.index(term) for term in key_terms if term in header] # Create output file writers with open(output_file1, 'w', newline='') as out_file1, \ open(output_file2, 'w', newline='') as out_file2: writer1 = csv.writer(out_file1) writer2 = csv.writer(out_file2) # Write the header row to both output files writer1.writerow(header) writer2.writerow(header) # Iterate through the input CSV file for row in reader: contains_key_terms = False # Check if any of the key terms are present in the row for index in key_term_indices: if row[index]: contains_key_terms = True break # Write the row to the appropriate output file if contains_key_terms: writer1.writerow(row) else: writer2.writerow(row) # Example usage split_csv('input.csv', 'output1.csv', 'output2.csv', ['key term 1', 'key term 2'])