2016-11-09 151 views
1

我有一个字符串形式以下值csv文件:不能字符串转换为浮动

'838.5', 
'830.090027', 
'820', 
'827.559998', 
'822.880005' 

和我读这样的文件:

file = [] 
for line in open('project.csv'): 
    our_data = line.split(",") 

    data.append(our_data) 

我试图将这些转化为漂浮在下列方式:

data = [float(x) for x in file] 

但是当我运行程序我得到这个错误:

ValueError异常:无法将字符串转换为浮动。

我怎样才能解决,而无需编辑csv文件这个问题?

+1

你是如何读取文件? –

+0

'文件= [] 在开线( 'project.csv'): our_data = line.split( “”) data.append(our_data)' –

+0

你能添加到你的问题。对于那些想要帮助你的人来说,这会让事情变得更容易。 –

回答

0

原始文件包含引号和断裂线(\ n)的,但你只是试图摆脱破线(但仍尚未完成)。首先,你需要从split()输出提取字符串(引号和数字),第二你需要摆脱报价,然后用浮点(...)将它们转换为浮动:

for line in open('project.csv'): 
    our_data = line.split(",") 
    print our_data 
    our_data = our_data[0][1:-1] 
    print our_data 
    print float(our_data) 

会给你的输出:

["'838.5'", '\n'] 
838.5 
838.5 
["'830.090027'", '\n'] 
830.090027 
830.090027 
["'820'", '\n'] 
820 
820.0 
["'827.559998'", '\n'] 
827.559998 
827.559998 
["'822.880005'"] 
822.880005 
822.880005 
1

始终对皮肤一只猫的方法不止一种,但这里是我会怎么做:

# Read the entire contents of the file into a string (`numbers`). 
# This includes newline characters and single-quotes. 
with open('project.csv') as infile: 
    numbers = infile.read() 

# Then remove the newline characters and single-quotes 
# (replace each with the empty string, thus removing them) 
# resulting in a string with numbers separated by commas 
# e.g., `123.3,45.9,39.1` 
numbers = numbers.replace("'","").replace("\n","") 

# Then create a new list by splitting the string on comma 
# and converting each individual item to a float 
numbers = [float(num) for num in numbers.split(',')] 

注:

  • 如果该文件是非常大的,你可能要重复行由行而不是读取整个文件。

  • 如果输入的文件可能包含格式错误,你必须要更小心,以避免意外的例外

0

您似乎有一些关于如何正确打开和分割您的文件的困惑。这应该工作。你的问题是你从文件中读取每一行,然后尝试分割它。你的实际追加到data是这样的:

['838.5', ',']

,然后尝试将其转换为一个浮动,这当然意味着Python会引发一个错误。相反,请读入整个文件,然后将其分开。过滤掉任何不是一个数字,然后转换那些花车:中floats

with open('project.csv') as file: 
    file = file.readlines() 

file = [el[1:-1] for line in file for el in line.split(',')] 
floats = [float(el) for el in file if el] 

值:

[838.5, 830.090027, 820.0, 827.559998, 822.880005]