gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
Write me some code that sends a row from a csv file to another csv file removing it from…
- User
Write me some code that sends a row from a csv file to another csv file removing it from the first.
- Assistant
Sure! Here's an example of how you can achieve that using Python's
csvmodule:import csv def move_row(source_file, destination_file, row_index): # Read from source file with open(source_file, 'r', newline='') as file: reader = csv.reader(file) rows = list(reader) if row_index < 0 or row_index >= len(rows): print("Invalid row index!") return # Extract the row to be moved row_to_move = rows[row_index] # Remove the row from the rows list rows.pop(row_index) # Write to destination file with open(destination_file, 'w', newline='') as file: writer = csv.writer(file) writer.writerows(rows) print("Row moved successfully!") # Example usage source_file = 'source.csv' destination_file = 'destination.csv' row_index_to_move = 2 move_row(source_file, destination_file, row_index_to_move)In this code, you need to specify the paths of the source and destination CSV files. You also need to provide the index of the row you want to move (0-based index).