【问题标题】:Reading a CSV file using Python 3使用 Python 3 读取 CSV 文件
【发布时间】:2016-04-06 17:52:35
【问题描述】:
我正在学习如何使用 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'])
【问题讨论】:
标签:
python
python-3.x
csv
【解决方案1】:
一个简单的“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'])
【解决方案2】:
您可以在读取行时检查值。
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'])
【解决方案3】:
您逐行阅读并使用显式检查来过滤您想要处理的那些。例如,然后将它们添加到数组中,或者就地处理。