搜索CSV文件python

时间:2014-03-07 12:14:09

标签: python csv

我已经编写了一个程序来调用文件中的汇率,但它打印到达行的输出,有一个逻辑错误,但我找不到它。

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")

文件:

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

2 个答案:

答案 0 :(得分:2)

如果我正确理解您的问题,问题是它会打印"Sorry..."行,即使它在文件中找到了货币。为防止这种情况发生,您可以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")

这样,else块只会在循环正常退出时执行,即没有break

答案 1 :(得分:2)

您需要指定分隔符或csv文件;对我而言,它看起来像制表符分隔,所以:

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

然后你必须明白break只是打破了循环,而不是整个程序。为此,您需要使用sys.exit()。但更好的解决方案是else循环的for子句:

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")