2014-03-07 76 views
1

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

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 
+0

什么分隔符是您使用?默认为逗号,但在文件中没有看到任何逗号。 –

+0

你能否详细说明一下,比如预期的输出结果和你得到的结果。 –

+0

excel中的CSV(逗号分隔) – user3165683

回答

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执行。

+0

您击败了我12秒! >; - ] – Alfe

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

哦,你在你的问题中将选项卡更改为逗号。然后使用'delimiter =',''(当然也可以是默认值)。 – Alfe