how do you read data in csv file and print specifi

2019-09-07 02:04发布

问题:

in my program i ask the user for a number and then proceed to read a csv file using DictReader. I want to output the values in the csv file that are larger then the users number....

import csv

limit_amount = raw_input("Please Enter a Limit Amount: ")

with open("transactionsample.csv","rb") as my_file:
    reader = csv.DictReader(my_file)
    for row in reader:
        print row

回答1:

import csv

limit_amount = int(raw_input("Please Enter a Limit Amount: ")) #convert limit_amount from string to int

with open("transactionsample.csv") as my_file: #rb is really unnecessary
    reader = csv.DictReader(my_file)
    for row in reader:
        for k in row: #check each cell
            if row[k].isdigit() and int(row[k]) > limit_amount: #validation and comparison 
                print row[k]


回答2:

What you want to do is to test the value from you row you are reading against the user input limit_amount. For that you need to know which 'column' you're comparing the user input against, let's say the value you're looking for is at index 2:

import csv

limit_amount = raw_input("Please Enter a Limit Amount: ")

with open("transactionsample.csv","rb") as my_file:
    reader = csv.DictReader(my_file)
    for row in reader:
        if row[2] >= limit_amount: # you might have to change the if condition to match exactly what you want
            print row


标签: python csv input