0

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)
5
  • 2
    Why do you import the library csv, but not user the csv.reader class? Commented Jul 16, 2012 at 6:26
  • 1
    for stock in stocks: means stock would be a str, so it will have no .extend() method. This can't be the code you are running Commented Jul 16, 2012 at 6:32
  • 1
    Please put the code which we can run and generate your issue in our system. Then and only then we can solve your problem. As mention in above comment stock is string and it has no .extend() method. Commented Jul 16, 2012 at 6:37
  • As well as the code you're actually running - some sample data would be useful. Commented Jul 16, 2012 at 6:38
  • It is now corrected. Sorry about that. Commented Jul 16, 2012 at 6:41

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

That would be it exactly. Thanks so much. My Python needs some practice to say the least.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.