使用Python 3读取CSV文件 [英] Reading a CSV file using Python 3

查看:159
本文介绍了使用Python 3读取CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


推荐答案

一个简单的if语句就足够了。请参见控制流文档。

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

这篇关于使用Python 3读取CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆