2016-01-02 131 views
5

我正在学习如何使用Python 3读取CSV文件,并且一直在玩弄我的代码,并设法读取整个文档或某些列,但是我正在尝试读取只有某些包含特定值的记录。使用Python读取CSV文件3

例如,我想读取汽车是蓝色的所有记录,我将如何让它只读取那些记录?我无法弄清楚这一点,并会很感激任何帮助或指导!

import csv 

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

的[我如何读取和写入使用Python CSV文件?(可能的复制http://stackoverflow.com/questions/41585078/how-do-i-read-and-write-csv-files -with-python) –

回答

6

一个简单的“if”语句就足够了。请参阅control flow文档。

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

谢谢!我在这样一个脑海中瞬间真的很尴尬 – user5508371

0

您逐一读取每一行,并使用显式检查来筛选要处理的行。然后将它们添加到数组中,或者将其处理到位。

+0

我该怎么做? – user5508371

1

您可以在读取行时检查值。

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