I'm reading in a zipped csv file and would like to extract only specific columns without using pandas. My current code only returns a list for the first list comprehension, but not for the following ones. How can I extract multiple columns while using a context manager?
Input file:
col1,col2,col3
1,2,3
a,b,c
My code
import gzip
import csv
import codecs
with gzip.open(r"myfile.csv.gz", "r") as f:
content = csv.reader(codecs.iterdecode(f, "utf-8"))
col_2 = [row[1] for row in content] # Returns [2, "b"]
col_3 = [row[2] for row in content] # Returns []
Expected output:
col_2: [2, "b"]
col_3: [3, "c"]