写入CSV文件时出现TypeError:writerows()参数必须可迭代

0 投票
1 回答
5025 浏览
提问于 2025-04-18 02:01

我正在尝试写一个货币转换器,这个程序有代码和一个CSV文件,CSV文件可以被编辑,以便在不同的使用者之间保存新的汇率。但是我在写入文件和更改汇率时遇到了问题:

 def change():
    print()
    print()
    print()
    print("1) Change existing exchange rate.")
    print("2) Add new exchange rates.")
    print("3) Quit.")
    exRtFile = open ('exchangeRate.csv')
    exchReader = csv.reader(exRtFile)
    exchWriter = csv.writer(exRtFile)
    loop2=0
    while loop2==0:
        selected=int(input("Please select an option: "))
        if selected == 1:
            change = input("What rate would you like to change: ")
            changeRt = float(input("What would you like to change the rate to: "))
            for row in exchReader:
                currency = row[0]
                if currency == change:
                    crntRt = row[1]
                    crntRt = changeRt
                    exchWriter.writerows(crntRt)

下面是一个输入/输出的例子:

1) Change existing exchange rate.
2) Add new exchange rates.
3) Quit.
Please select an option: 1
What rate would you like to change: Euro
What would you like to change the rate to: 1.23
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    converter()
  File "py", line 21, in converter
    change()
  File "py", line 91, in change
    exchWriter.writerows(crntRt)
TypeError: writerows() argument must be iterable

1 个回答

0

writeRows()这个函数本身是需要一个变量,这个变量里要装着很多值,每个值代表要写入输出文件的一行数据。

因为你给writerows()的是一个单独的float值,所以它就告诉你,它不知道怎么把这个值变成多行数据。在“Python的说法”中,must be iterable的意思是“我不知道怎么从你给我的这个东西里提取出多个值”。

你的代码里可能还有其他问题。特别是:

 crntRt = row[1]
 crntRt = changeRt
 exchWriter.writerows(crntRt)

这让我觉得你可能期待在输出中看到row[1]的值,但实际上你不会看到,因为下一行代码把这个值用新的汇率给覆盖掉了。

撰写回答