0

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.

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.