Skip to content Skip to sidebar Skip to footer

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

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

Solution 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

Post a Comment for "How Do You Read Data In Csv File And Print Specific Ones?"