用于将美元兑换成日元的Python编码失败

时间:2018-06-09 17:22:41

标签: python python-3.x

以下代码无效。以下代码的主要目的是将美元兑换成日元。收据信息写在Jun7.csv中,我想把计算结果放到Jun7.txt中。希望我的解释有意义。感谢您的帮助。

with open('Jun7.csv', encoding='utf-8') as f:
    for row in f:
        columns = row.rstrip().split(',')
        name = columns[0]
        price = float(columns[1])

        multi = price * 110

with open('Jun7.txt', 'a', encoding='utf-8') as wf:
        wf.write(name + ', ' + str(multi))

为记录,下面是Jun7.csv的内容

WHITE WAVE SLK SY VA W, 3.85
GG STMR MX VEG x 2, 3.98
STFFER BKD CHKN, 3.39
TINY TWIST PRETZ, 3.29
ROTISSERE CHICKEN, 6.99
BANANAS, 1.48
KENTWOOD DISTLD WTR, 1.48

3 个答案:

答案 0 :(得分:3)

您没有将namemulti保存在单独的变量中,因此您最终只会编写已查看的最后一个值。

考虑按如下方式修改代码:

yen_prices = []
with open('Jun7.csv') as dollar_file:
    for dollar_entry in dollar_file:
        columns = dollar_entry.rstrip().split(',')
        name = columns[0]
        dollar_price = float(columns[1])

        yen_entry = name, dollar_price * 110
        yen_prices.append(yen_entry)

with open('Jun7.txt', 'w') as yen_file:
    for yen_entry in yen_prices:
        yen_file.write("{}, {}\n".format(yen_entry[0], yen_entry[1]))

答案 1 :(得分:2)

您计算输入文件中每一行的日元价格,但您只写一行(即使用最后一个计算值)。 您可以在同一个for循环中执行所有操作

with open('Jun7.csv', encoding='utf-8') as f:
    with open('Jun7.txt', 'a', encoding='utf-8') as wf:
        for row in f:
            columns = row.rstrip().split(',')
            name = columns[0]
            price = float(columns[1])

            multi = price * 110
            wf.write(name + ', ' + str(multi))

答案 2 :(得分:2)

问题在于您的操作顺序。按原样,您的代码计算第一行的namepricemulti,然后用第二行覆盖所有这些值,然后用第三行覆盖它们。等等,直到它到达最后一排。

然后 它会name, multiJun7.txt,即它只会写出从Jun7.csv的最后一行获取的值。

你需要以某种方式存储来自每一行的信息,所以它们都可以在最后写入,或者只需重新排列几行,就可以在扫描每一行时写入:

with open('Jun7.csv', encoding='utf-8') as f:
    with open('Jun7.txt', 'a', encoding='utf-8') as wf: #Open both files at same time
        for row in f:
            columns = row.rstrip().split(',')
            name = columns[0]
            price = float(columns[1]) 
            multi = price * 110

            wf.write(name + ', ' + str(multi)) #Write info at end of for loop
                                               #before overwriting variables
                                               #in next iteration