str在csv python中浮动错误

时间:2013-05-27 22:32:31

标签: python arrays csv python-2.7 floating-point

我正在尝试打开一个10列x 100行的csv文件,我首先要将它换成100列x 10行,我相信我正确地使用了zip函数,然后生成10个数组每个都有100个花车。

output = []
with open("undercurve.csv",'rU') as f5:
    reader = csv.reader(f5, delimiter= ',')
    reader1 = zip(*reader)
    for row in reader1:
        value = 0 
        for i in row:
            value = float(i)
            output.append(i)

然而,当我运行它时,我得到了一个

    ValueError
    Traceback (most recent call last)

        174             else:
        175                 filename = fname
    --> 176             exec compile(scripttext, filename, 'exec') in glob, loc
        177     else:
        178         def execfile(fname, *where):

    C:\Users\Robert\Downloads\May.py in <module>()
        142         value = 0
        143         for i in row:
    --> 144             value = float(i)
        145             output.append(i)
        146 
    ValueError: could not convert string to float. 

我猜这是来自前一部分:

i = 0
with open("undercurve.csv",'w') as f3:
    for i in undercurve_1:
        mean = i
        variance = .2
        points = undercurve(1000)[:10]
        for item in points:
            x = str(item)
            f3.write(x + ",")
        f3.write("\n")     

如果我尝试使用x = float(item),我会收到错误:

    TypeError                                 
    Traceback (most recent call last)
    174             else:
    175                 filename = fname
--> 176             exec compile(scripttext, filename, 'exec') in glob, loc
    177     else:
    178         def execfile(fname, *where):

C:\Users\Robert\Downloads\May.py in <module>()
    130         for item in points:
    131             x = float(item)
--> 132             f3.write(x + ",")
    133         f3.write("\n")
    134 
    TypeError: unsupported operand type(s) for +: 'float' and 'str'. 

我不确定在这种情况下该怎么做。

0.485863651248,0.0387115424974,0.287431660408,0.368734594828,0.618990463984,0.112220965205,0.418700402941,0.193754757929,0.573411295973,-0.192370410069,
-1.42282833703,-1.52808081061,-1.03071829996,-1.00330662742,-1.23896275168,-1.09742340137,-0.940839402591,-0.918657969034,-1.37832945051,-0.932452513278,

这些只是undercurve.csv文件的前两行

1 个答案:

答案 0 :(得分:1)

显然,文件每行的结尾都以逗号结尾。这使得''(空字符串)出现。 float('')为您提供ValueError。