本文介绍了添加一行到CSV文件 - TypeError:必须是str,不是元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试以格式将行添加到我的CSV文件; 名称,价值。
以下是CSV文件:

Trying to add a row to my CSV file in the format; "name, value".Here is the CSV file:

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

这是代码的一部分,为CSV文件添加一行:

Here is the part of code which is reponsible for adding a row to the CSV file:

def add():         
    addCurrency = input("What currency would you like to add: ")
    newRt = float(input("Please enter the new exchange rate from Pound Sterling: "))
    adding = str(addCurrency), str(newRt)
    file = open('exchangeRate.csv', 'a')
    file.write(adding)


推荐答案

那么,在问之前做一些测试。在 file.write(添加)之前,您可以输入打印(添加) (添加.__ repr __()),看看你的添加实例是什么是Pythons问题。你会看到它是一个元组的('Euro','5.5')。 True如果Python抱怨它需要一个字符串而不是一个元组,你传递一个元组。首先,不要转换为浮动 newRt 输入,因为你需要它作为字符串。你需要这里是 adding =','。join((addCurrency,newRt))+'\\\
'或 adding ='{ ,{} \\\
'.format(addCurrency,newRt)或 adding = addCurrency +','+ newRt +'\\\
' 。尝试找出这样的简单问题之前质疑SO。阅读文档的教程。

Well, do some testing before asking. Before file.write(adding) you could have put a print(adding) of print(adding.__repr__()) to see what is Pythons problem with your adding instance. You would have seen it is like ('Euro', '5.5') which is a tuple. True if Python complains it needs a string instead of a tuple you passed there a tuple. First, don't convert to float the newRt input since you need it as a string either. What you need here is adding = ','.join((addCurrency, newRt)) + '\n' or adding = '{},{}\n'.format(addCurrency, newRt) or adding = addCurrency + ',' + newRt + '\n'. Try to figure out simple problems like this one before questioning SO. Read the tutorial of the documentation.

这篇关于添加一行到CSV文件 - TypeError:必须是str,不是元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 20:07