user1526586
user1526586

Reputation: 93

Python repeating CSV file

I'm attempting to load numerical data from CSV files in order to loop through the calculated data of each stock(file) separately and determine if the calculated value is greater than a specific number (731 in this case). However, the method I am using seems to make Python repeat the list as well as add quotation marks around the numbers ('500'), as an example, making them strings. Unfortunately, I think the final "if" statement can't handle this and as a result it doesn't seem to function appropriately. I'm not sure what's going on and why Python what I need to do to get this code running properly.

    import csv
    stocks = ['JPM','PG','GOOG','KO']
    for stock in stocks:
        Data = open("%sMin.csv" % (stock), 'r')
        stockdata = []
        for row in Data:
           stockdata.extend(map(float, row.strip().split(',')))
           stockdata.append(row.strip().split(',')[0])
        if any(x > 731 for x in stockdata):
            print "%s Minimum" % (stock)

Upvotes: 0

Views: 454

Answers (1)

Jon Clements
Jon Clements

Reputation: 142126

Currently you're adding all columns of each row to a list, then adding to the end of that, the first column of the row again? So are all columns significant, or just the first?

You're also loading all data from the file before the comparison but don't appear to be using it anywhere, so I guess you can shortcut earlier...

If I understand correctly, your code should be this (or amend to only compare first column).

Are you basically writing this?

import csv

STOCKS = ['JPM', 'PG', 'GOOG', 'KO']

for stock in STOCKS:
    with open('{}Min.csv'.format(stock)) as csvin:
        for row in csv.reader(csvin):
            if any(col > 731 for col in map(float, row)):
                print '{} minimum'.format(stock)
                break

Upvotes: 1

Related Questions