Delete specific column from csv file with Python
I have a function that selects the index of the columns I want to use (automatically, based on the text in the header of the column), the result is a list like the ones in the following example:
>>>print(usable_data_index)
[0, 2, 5, 7] #It may be like this
[0, 3, 4, 5, 6, 10] #Or like this one
[1, 2] #Or this
#It may vary.
Then I want to write to the new file only the columns which indexes are in usable_data_index (this is what I don't know how to do). I know I can write specific columns this way:
for row in csv_reader:
csv_writer.writerow((row[0], row[1], row[3], row[4]))
But in that case I have to specify the indexes manually.
Solution 1:
Inside your for loop add a tuple called rows_to_add and pass it to csv writer:
rows_to_add=(row[index] for index in usable_data_index)
csv_writer.writerow(rows_to_add)