user3165683
user3165683

Reputation: 367

Searching a CSV file python

I have written a program to calll exchange rates from a file but it prints an output fo reach row, there is a logic error but i cant't find it.

import csv
exRtFile = open ('exchangeRate.csv')
exchReader = csv.reader(exRtFile)
newCurrency = raw_input("Please enter the currency you would like to convert to: ")
for row in exchReader:
        currency = row[0]
        if currency == newCurrency:
            newRt = row[1]
            print(newRt)
            break

print("Sorry, that is not a valid currency")

file:

Pound Sterling,1
Euro,1.22
US Dollar,1.67
Japanese Yen,169.948

Upvotes: 1

Views: 125

Answers (2)

Alfe
Alfe

Reputation: 59616

You need to specify the delimiter or your csv file; to me it looks like tab-delimited, so:

exchReader = csv.reader(exRtFile, delimiter='\t')

Then you have to understand that break is only breaking out of the loop, not out of the whole program. For that you will need to use sys.exit(). But a nicer solution is the else clause for for loops:

for row in exchReader:
    currency = row[0]
    if currency == newCurrency:
        newRt = row[1]
        print(newRt)
        break
else:
    print("Sorry, that is not a valid currency")

Upvotes: 2

tobias_k
tobias_k

Reputation: 82949

If I understand your question correctly, the problem is that it prints the "Sorry..." line even when it finds the currency in the file. To prevent this, you can add an else to the for loop.

for row in exchReader:
    currency = row[0]
    if currency == newCurrency:
        newRt = row[1]
        print(newRt)
        break
else:
    print("Sorry, that is not a valid currency")

This way, the else block will only be executed when the loop is exited normally, i.e. without break.

Upvotes: 2

Related Questions