Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a CSV file using Python 3

Tags:

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']) 
like image 675
user5508371 Avatar asked Jan 02 '16 17:01

user5508371


People also ask

How do I read and print a CSV file in Python?

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.

How do I read a CSV file from specific data in Python?

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.


2 Answers

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']) 
like image 110
Kevin Avatar answered Sep 21 '22 15:09

Kevin


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']) 
like image 31
Danny_ds Avatar answered Sep 20 '22 15:09

Danny_ds