简体   繁体   English

Python:如何从 csv 文件中仅打印正确的行

[英]Python: how to print only the lines that are true from csv file

As stated above.如上所述。 This is my csv file:这是我的 csv 文件:

class, time, duration, building

math, 10:55, 2hr, B01

religion, 3:45, 2hr, B02

PDHPDE, 12:05, 2hr, B03

history, 1:00, 2hr, B04

history extension, 11:00, 2hr, B05

I expected the result to be just 1 line printed from this code that I used我希望结果只是从我使用的这段代码中打印出来的 1 行

import csv

with open('sched.csv') as csvfile:

    sched = csv.reader(csvfile, delimiter=',')

    for row in sched:
        a = row[1]
        print(a == '10:55')

However, my output was:但是,我的 output 是:

False

False

True

False

False

I just want to print out the 'true' line as "math, 10:55, 2hr, B01"我只想将“真实”行打印为“math, 10:55, 2hr, B01”

It should be:它应该是:

import csv

with open('sched.csv') as csvfile:

    sched = csv.reader(csvfile, delimiter=',')

    for row in sched:
        a = row[1]
        if (a == '10:55'):
            print(row)

Instead of printing the result of (a == '10:55') which is either True or False for each row, you should check if it is True, then print the whole row.您应该检查它是否为真,然后打印整行,而不是打印 (a == '10:55') 的结果(每行为真或假)。

just add an if.只需添加一个 if。

i think something like this would work我认为这样的事情会奏效

import csv

with open('sched.csv') as csvfile:

    sched = csv.reader(csvfile, delimiter=',')

    for row in sched:
        a = row[1]
        if a == '10:55':
            print(a == '10:55')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM