简体   繁体   中英

Reading a CSV file using Python 3

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'])

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'])

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'])

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM