使用 Python 3 读取 CSV 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34568774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 15:10:36  来源:igfitidea点击:

Reading a CSV file using Python 3

pythonpython-3.xcsv

提问by user5508371

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.

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

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

采纳答案by Kevin

A simple "if" statement should suffice. See control flowdocs.

一个简单的“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'])

回答by Csene

You read each row one by one and use an explicit check to filter those that you want to deal with. Then add them to an array for example, or process it in place.

您逐行阅读并使用显式检查来过滤您想要处理的那些。例如,然后将它们添加到数组中,或就地处理。

回答by Danny_ds

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