Write me some python 3 that reads rows from CSV1 and deletes them in CSV2
- User
Write me some python 3 that reads rows from CSV1 and deletes them in CSV2
- Assistant
Certainly! Here's an example code that reads rows from
CSV1and deletes them inCSV2using thecsvmodule in Python:pythonimport csv csv1_filename = 'CSV1.csv' csv2_filename = 'CSV2.csv' # Read rows from CSV1 rows_to_delete = [] with open(csv1_filename, 'r') as csv1_file: csv_reader = csv.reader(csv1_file) for row in csv_reader: rows_to_delete.append(row) # Delete rows from CSV2 rows_after_deletion = [] with open(csv2_filename, 'r') as csv2_file: csv_reader = csv.reader(csv2_file) for row in csv_reader: if row not in rows_to_delete: rows_after_deletion.append(row) # Write the updated rows to CSV2 with open(csv2_filename, 'w', newline='') as csv2_file: csv_writer = csv.writer(csv2_file) csv_writer.writerows(rows_after_deletion) print('Rows from CSV1 deleted in CSV2 successfully.') - User
Make this a function which takes the args csv1 and csv2
- Assistant
Certainly! Here's the modified code that wraps the logic into a function that takes the arguments
csv1andcsv2:pythonimport csv def delete_rows_in_csv(csv1, csv2): # Read rows from CSV1 rows_to_delete = [] with open(csv1, 'r') as csv1_file: csv_reader = csv.reader(csv1_file) for row in csv_reader: rows_to_delete.append(row) # Delete rows from CSV2 rows_after_deletion = [] with open(csv2, 'r') as csv2_file: csv_reader = csv.reader(csv2_file) for row in csv_reader: if row not in rows_to_delete: rows_after_deletion.append(row) # Write the updated rows to CSV2 with open(csv2, 'w', newline='') as csv2_file: csv_writer = csv.writer(csv2_file) csv_writer.writerows(rows_after_deletion) print(f"Rows from {csv1} deleted in {csv2} successfully.") # Example usage csv1_filename = 'CSV1.csv' csv2_filename = 'CSV2.csv' delete_rows_in_csv(csv1_filename, csv2_filename) - User
Could you change all open statements to having utf-8 encoding?
- Assistant
Certainly! Here's the modified code with the open statements updated to use the utf-8 encoding:
pythonimport csv def delete_rows_in_csv(csv1, csv2): # Read rows from CSV1 rows_to_delete = [] with open(csv1, 'r', encoding='utf-8') as csv1_file: csv_reader = csv.reader(csv1_file) for row in csv_reader: rows_to_delete.append(row) # Delete rows from CSV2 rows_after_deletion = [] with open(csv2, 'r', encoding='utf-8') as csv2_file: csv_reader = csv.reader(csv2_file) for row in csv_reader: if row not in rows_to_delete: rows_after_deletion.append(row) # Write the updated rows to CSV2 with open(csv2, 'w', newline='', encoding='utf-8') as csv2_file: csv_writer = csv.writer(csv2_file) csv_writer.writerows(rows_after_deletion) print(f"Rows from {csv1} deleted in {csv2} successfully.") # Example usage csv1_filename = 'CSV1.csv' csv2_filename = 'CSV2.csv' delete_rows_in_csv(csv1_filename, csv2_filename)