22

I am learning how to read CSV files using Python 3, and have been playing around with my code and have managed to read either the whole document or certain columns, however I am trying to now read only certain records that contain a certain value.

For example I want to read all records where the car is blue, how would I make it read only those records? I can't figure this out and would be grateful for any help or guidance!

import csv

with open('cars.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(row['ID'], row['Make'], row['Colour'])
1

3 Answers 3

33

A simple "if" statement should suffice. See control flow docs.

import csv

with open('Cars.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        if row['Colour'] == 'blue':
            print(row['ID'] ,row ['Make'],row ['Colour'])
Sign up to request clarification or add additional context in comments.

Comments

3

You can check the values while reading the rows.

with open('Cars.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
     // check your values here - if car = blue 
     // do something with blue cars.
     print(row['ID'] ,row ['Make'],row ['Colour'])

Comments

-1

You read each row one by one and use an explicit check to filter those that you want to deal with. Then add them to an array for example, or process it in place.

1 Comment

How would I do this?

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.