如何在Python中读取CSV文件中的特定行

如何在Python中读取CSV文件中的特定行,python,csv,Python,Csv,在过去的几天里,我一直在寻找帮助,但什么也没找到 我现在正在攻读计算机科学A级。这个项目是一个货币转换器,我想知道如何让用户输入货币代码,然后让程序获取这些信息,并将其与CSV文件进行比较。如果货币代码在文件中,那么我需要程序从输入中获取与货币代码匹配的转换率,并在求和/等式中使用该转换率来完成转换。我尝试了几种不同的方法来尝试和实现CSV文件,但我似乎无法让它工作 我正在使用Python 3.5.2 我要求的不是完整的代码,只是一些如何实现这样一个CSV文件的示例 这是我的一个CSV文件的示例

在过去的几天里,我一直在寻找帮助,但什么也没找到

我现在正在攻读计算机科学A级。这个项目是一个货币转换器,我想知道如何让用户输入货币代码,然后让程序获取这些信息,并将其与CSV文件进行比较。如果货币代码在文件中,那么我需要程序从输入中获取与货币代码匹配的转换率,并在求和/等式中使用该转换率来完成转换。我尝试了几种不同的方法来尝试和实现CSV文件,但我似乎无法让它工作

我正在使用Python 3.5.2

我要求的不是完整的代码,只是一些如何实现这样一个CSV文件的示例

这是我的一个CSV文件的示例:

Currency,        Code,  Rate
Canadian Dollar, CAD,   1.3457
Swiss Franc,     CHF,   1.0129
British Pounds,  GBP,   0.8056
Japanese Yen,    JPY,   111.52
Bitcoin,         BTC,   0.001351
我的第一个程序使用if、elif和else语句来实现转换,但是因为我很早就完成了任务,所以我被告知使用CSV文件

这是最初的代码:

def Amount_Input():
    while True:
        try:
            global amount
            amount = float(input("Enter amount to be converted:"))
            Currency_From()
            break
        except ValueError:
            print("Invalid Entry, Please enter a valid entry as a decimal number.")
            continue


def Currency_From():
    currencyInput1 = input("Enter the currency you wish to convert from:")
    if currencyInput1 in ['USD', 'usd']:
        USD()
    elif currencyInput1 in ['GBP', 'gbp']:
        GBP()
    elif currencyInput1 in ['EUR', 'eur']:
        EUR()
    elif currencyInput1 in ['BTC', 'btc']:
        BTC()
    else:
        print("Invalid entry")
        Currency_From()


def USD():
    currencyInput2 = input("Enter the currency you want to convert to:")
    if currencyInput2 in ['GBP', 'gbp']:
        print("You are converting", amount, "USD to GBP.")
        converted_amount = amount*0.81
        print(converted_amount)
    elif currencyInput2 in ['EUR', 'eur']:
        print("You are converting", amount, "USD to EUR.")
        converted_amount = amount*0.94
        print(converted_amount)
    elif currencyInput2 in ['BTC', 'btc']:
        print("You are converting", amount, "USD to BTC.")
        converted_amount = amount*0.0013
        print(converted_amount)
    else:
        print("Invalid Entry")
        USD()


def GBP():
    currencyInput2 = input("Enter the currency you want to convert to:")
    if currencyInput2 in ['USD', 'usd']:
        print("You are converting", amount, "GBP to USD.")
        converted_amount = amount*1.24
        print(converted_amount)
    elif currencyInput2 in ['EUR', 'eur']:
        print("You are converting", amount, "GBP to EUR.")
        converted_amount = amount*1.17
        print(converted_amount)
    elif currencyInput2 in ['BTC', 'btc']:
        print("You are converting", amount, "GBP to BTC.")
        converted_amount = amount*0.0017
        print(converted_amount)
    else:
        print("Invalid Entry")
        GBP()


def EUR():
    currencyInput2 = input("Enter the currency you want to convert to:")
    if currencyInput2 in ['USD', 'usd']:
        print("You are converting", amount, "EUR to USD.")
        converted_amount = amount*1.06
        print(converted_amount)
    elif currencyInput2 in ['GBP', 'gbp']:
        print("You are converting", amount, "EUR to GBP.")
        converted_amount = amount*0.85
        print(converted_amount)
    elif currencyInput2 in ['BTC', 'btc']:
        print("You are converting", amount, "EUR to USD.")
        converted_amount = amount*0.0014
        print(converted_amount)
    else:
        print("Invalid Entry")
        EUR()


def BTC():
    currencyInput2 = input("Enter the currency you want to convert to:")
    if currencyInput2 in ['USD', 'usd']:
        print("You are converting", amount, "BTC to USD.")
        converted_amount = amount*746.20
        print(converted_amount)
    elif currencyInput2 in ['GBP', 'gbp']:
        print("You are converting", amount, "BTC to GBP.")
        converted_amount = amount*600.89
        print(converted_amount)
    elif currencyInput2 in ['EUR', 'eur']:
        print("You are converting", amount, "BTC to EUR.")
        converted_amount = amount*704.36
        print(converted_amount)
    else:
        print("Invalid Entry")
        BTC()


print(Amount_Input())
这是我的建议

你可以在第一个例子中看到,他们一行一行地读。(如果是普通csv,则不需要指定分隔符或引号) 对于您的文件,它应该如下所示:

import csv
with open('currency.csv', 'rb') as csvfile:
    currencyreader = csv.reader(csvfile)
    for row in currencyreader:
        print row
输出将是:

['Currency', 'Code', 'Rate']
['Canadian Dollar  CAD 1.3457', 'CAD', '1.3457']
['Swiss Franc  CHF 1.0129', 'CHF', '1.0129']
['British Pounds   GBP  0.8056', 'GBP', '0.8056']
['Japanese Yen   JPY  111.52', 'JPY', '111.52']
['Bitcoin  BTC 0.001351', 'BTC', '0.001351']
将打开的文件设置为csvfile对象。然后将文件内容读入currencyreader对象。然后一行一行地循环

您必须将函数从读取用户输入更改为将行作为参数


此外,这可能只是个人偏好,但我会重构您的代码以删除while True,因为它们会让我畏缩

我知道,对于一个学校项目,您需要练习python技能,但像这样的东西已经被现有的库捕获了。Numpy可能是任何有数字的东西都可以去图书馆的人。以下是我将如何处理您的项目:

from io import StringIO
import numpy as np
下一行执行所有文件读取和解码

d = np.recfromcsv('currencies.csv', delimiter=',')
现在,您可以使用“d”访问您的个人货币

print( d[1] )   # shows: (b'Swiss Franc', b'     CHF', 1.0129)
print( d[1][2] )# shows: 1.0129

如果我这样做的话,我会从一开始就阅读整个文件,并创建一个字典,将货币代码映射到汇率。也许你可以下载这个并检查它们的实现: