There is a CSV file with many rows and 30 columns. What I wanted is to get the data from columns 3,6, and 15 and then save it in a list.
Using Python how can I achieve this so that I dont have to load the entire file into the memory?
Any suggestions?
>Solution :
I guess in python you can use ‘islice’ function from the ‘itertools’ model.
Here’s an example code for this:
import csv
from itertools import islice
columns_to_extract = [2, 5, 14]
with open('filename.csv', 'r') as f:
reader = csv.reader(f)
extracted_data = [[] for _ in range(len(columns_to_extract))]
for row in islice(reader, 1, None): # Skip header row (if any)
for i, col_idx in enumerate(columns_to_extract):
extracted_data[i].append(row[col_idx])