简体   繁体   中英

how do you read data in csv file and print specific ones?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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