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'])
csv file in reading mode using open() function. Then, the csv. reader() is used to read the file, which returns an iterable reader object. The reader object is then iterated using a for loop to print the contents of each row.
This can be done with the help of the pandas. read_csv() method. We will pass the first parameter as the CSV file and the second parameter the list of specific columns in the keyword usecols. It will return the data of the CSV file of specific columns.
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'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With