使用Python 3读取CSV文件

时间:2023-01-05 08:46:52

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

3 个解决方案

#1


12  

A simple "if" statement should suffice. See control flow docs.

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

#2


1  

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

#3


0  

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.

您逐个读取每一行,并使用显式检查来过滤您想要处理的那些。然后将它们添加到一个数组中,或者在适当的位置进行处理。

#1


12  

A simple "if" statement should suffice. See control flow docs.

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

#2


1  

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

#3


0  

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.

您逐个读取每一行,并使用显式检查来过滤您想要处理的那些。然后将它们添加到一个数组中,或者在适当的位置进行处理。