Reading a CSV file using Python 3

0 votes
I have recently learnt 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.  Now I am trying to 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?

import csv

with open('cars.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(row['ID'], row['Make'], row['Colour'])
Mar 26 in Python by ana1504.k
• 7,870 points
268 views

1 answer to this question.

0 votes
A simple "if" statement should suffice. you can try this :

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'])
answered Mar 26 by SDeb
• 13,160 points

Related Questions In Python

+1 vote
1 answer

Reading a large file, line by line in Python

The correct, fully Pythonic way to read ...READ MORE

answered Aug 21, 2018 in Python by Priyaj
• 56,520 points
53 views
0 votes
1 answer

Download a file over HTTP using Python

In Python 2, use urllib2 which comes ...READ MORE

answered Oct 22, 2018 in Python by Priyaj
• 56,520 points
66 views
0 votes
1 answer

How to use read a WSDL file from the file system using Python suds?

Hi, good question. It is a very simple ...READ MORE

answered Jan 21 in Python by Nymeria
• 3,520 points
461 views
0 votes
0 answers

cannot read a csv file in python

i am getting an error reading a ...READ MORE

Mar 5 in Python by Mohammad
• 3,060 points
19 views
0 votes
1 answer

Crawling after login in Python

You missed a few login data forms, ...READ MORE

answered Sep 7, 2018 in Python by Priyaj
• 56,520 points
327 views
0 votes
1 answer

Crawling after login in Python

You missed a few login data forms, ...READ MORE

answered Sep 14, 2018 in Python by Priyaj
• 56,520 points
35 views
0 votes
1 answer

“stub” __objclass__ in a Python class how to implement it?

You want to avoid interfering with this ...READ MORE

answered Sep 27, 2018 in Python by Priyaj
• 56,520 points
49 views
+1 vote
1 answer

How is raw_input() and input() in python3.x?

raw_input() was renamed to input() so now input() returns the exact string ...READ MORE

answered Oct 30, 2018 in Python by Priyaj
• 56,520 points
39 views
0 votes
1 answer

How to download a file over HTTP using Python?

In Python 2, use urllib2 which comes ...READ MORE

answered Oct 18, 2018 in Python by SDeb
• 13,160 points
48 views
0 votes
1 answer

In Python, how do I read a file line-by-line into a list?

with open(fname) as f:     content = f.readlines() # you ...READ MORE

answered Oct 9, 2018 in Python by SDeb
• 13,160 points
113 views