从Python中的csv文件读取时,将String转换为Integer / float

时间:2017-11-27 10:50:44

标签: python python-3.x csv

我有一个文件,其中包括[" 75,000"," 500,000"," 255,000"]等数字。 我无法将这些作为整数或浮点数附加到List,我只能将其作为String追加。对我来说,它看起来是由于字符串值中的逗号。我可以将它打印为String但不对它们进行算术运算,因为它们是字符串。下面是我尝试将int追加到列表中。请帮助解决这个问题。

Money = []

with open('Money.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    for row in readCSV:
        Money.append(int(row[4]))

1 个答案:

答案 0 :(得分:0)

int不知道如何处理分隔逗号,您需要删除它们。

Money.append(int(row[4].replace(',', '')))

但是,如果csv文件包含小数值,您可能需要考虑使用float而不是int