Categories
Python Answers

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

Spread the love

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

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

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

To read specific columns from a csv file with csv module with Python, we can loop through the rows read from the csv and then put them in a dict.

For instance, we write

import csv
from collections import defaultdict

columns = defaultdict(list)

with open("file.txt") as f:
    reader = csv.DictReader(f)
    for row in reader:
        for (k, v) in row.items():
            columns[k].append(v)

print(columns["name"])

to open file.txt.

Then we read the contents into rows with

reader = csv.DictReader(f)

Then we loop through the rows with a for loop.

And we loop through the items with another for loop.

Then we append the items to an entry in columns with key k with append to append v.

Now we can get the values of the name column with columns['name'].

Conclusion

To read specific columns from a csv file with csv module with Python, we can loop through the rows read from the csv and then put them in a dict.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *