Menu Close

How to read specific columns from a csv file with the csv module?

Sometimes, we want to read specific columns from a csv file with the csv module.

In this article, we’ll look at how to read specific columns from a csv file with the csv module.

How to read specific columns from a the csv file with csv module?

To read specific columns from a csv file with the csv module, we can use list comprehension.

For instance, we write:

import csv

included_cols = [1]
csv_file = 'data.csv'

with open(csv_file, 'r') as csvfile:
    reader = csv.reader(csvfile)

    for row in reader:
        content = list(row[i] for i in included_cols)
        print(content)

We define the included_cols with the index of the columns we want to read.

Then we call open to open the file according to the csv_file path.

Next, we read the lines in the CSV by calling csv.reader with csvfile.

And then we loop through the rows with a for loop.

In the loop body, we get the row entry we want to include with row[i] for i in included_cols).

And then we print that with print.

Conclusion

To read specific columns from a csv file with the csv module, we can use list comprehension.

Posted in Python, Python Answers