我正在学习如何使用Python 3读取CSV文件,并且一直在使用我的代码,并设法读取整个文档或某些列,但是我现在尝试只读取包含特定值的某些记录。
例如,我想读取汽车为蓝色的所有记录,如何让它只读取那些记录?我无法弄清楚这一点,并感谢任何帮助或指导!
import csv
with open('cars.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
print(row['ID'], row['Make'], row['Colour'])
一个简单的“if”语句就足够了。看到 控制流 文档。
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'])
您可以在读取行时检查值。
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'])
您逐个读取每一行并使用显式检查来过滤您要处理的那些行。然后将它们添加到数组中,或者在适当的位置处理它。