Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 读取文本文件并将字符串转换为浮点_Python_Python 2.7_Ubuntu 14.04 - Fatal编程技术网

Python 读取文本文件并将字符串转换为浮点

Python 读取文本文件并将字符串转换为浮点,python,python-2.7,ubuntu-14.04,Python,Python 2.7,Ubuntu 14.04,我有一个名为“foo.txt”的文本文件,其中有一个数字列表,每行一个,例如: 0.094195 0.216867 0.326396 0.525739 0.592552 0.600219 0.637459 0.642935 0.662651 0.657174 0.683461 现在我想把这些数字读入Python列表。我的代码如下所示: x = [] file_in = open('foo.dat', 'r') for y in file_in.read().split('\n'): x

我有一个名为“foo.txt”的文本文件,其中有一个数字列表,每行一个,例如:

0.094195
0.216867
0.326396
0.525739
0.592552
0.600219
0.637459
0.642935
0.662651
0.657174
0.683461
现在我想把这些数字读入Python列表。我的代码如下所示:

x = []
file_in = open('foo.dat', 'r')
for y in file_in.read().split('\n'):
    x.append(float(y))
但这给了我一个错误:

ValueError: could not convert string to float

我做错了什么?

通常文件末尾有空行,所以您可能试图将空字符串强制转换为float

除了.read().split('\n')中的
文件,您可以使用:

for line in file_in.readlines():
  x.append(float(line))

方法
readlines
返回给定文件中所有行的列表,并跳过最后一个空行(如果存在)。

通常文件末尾有空行,所以可能您正试图将空字符串转换为float

除了.read().split('\n')中的
文件,您可以使用:

for line in file_in.readlines():
  x.append(float(line))
方法
readlines
返回给定文件中所有行的列表,并跳过最后一个空行(如果存在)。

编辑

评论人: 如果y:
为空,也可以使用
来消除
None
或空字符串

原始答案:

由于使用换行符作为分隔符,因此该操作失败,因此最后一个元素为空字符串

您可以添加
y.isdigit()
来检查y是否为数字

x = []
file_in = open('sample.csv', 'r')
for y in file_in.read().split('\n'):
    if y.isdigit():
        x.append(float(y))

您可以将
read().split(“\n”)
更改为
readlines()

从y中删除前导/尾随字符。它处理带有额外空格的行

for y in file_in:
    trimed_line = y.strip()  # leading or trailing characters are removed
编辑

评论人: 如果y:
为空,也可以使用
来消除
None
或空字符串

原始答案:

由于使用换行符作为分隔符,因此该操作失败,因此最后一个元素为空字符串

您可以添加
y.isdigit()
来检查y是否为数字

x = []
file_in = open('sample.csv', 'r')
for y in file_in.read().split('\n'):
    if y.isdigit():
        x.append(float(y))

您可以将
read().split(“\n”)
更改为
readlines()

从y中删除前导/尾随字符。它处理带有额外空格的行

for y in file_in:
    trimed_line = y.strip()  # leading or trailing characters are removed

您可以尝试使用默认的float函数

>>> float("1.1")
1.1
您还可以尝试使用pythontryelse语句,该语句将运行代码,直到捕获错误并运行else语句

try:
   try_this(whatever that might bring up a error)
except SomeException as exception:
   #Handle exception
else:
   return something

文件可能有一个空行结尾,这可能会产生错误。因此,请尝试使用Try-else语句。

您可以尝试使用默认的float函数

>>> float("1.1")
1.1
您还可以尝试使用pythontryelse语句,该语句将运行代码,直到捕获错误并运行else语句

try:
   try_this(whatever that might bring up a error)
except SomeException as exception:
   #Handle exception
else:
   return something

文件可能有一个空行结尾,这可能会产生错误。尝试使用Try-else语句,因为它。

我认为您的字符串如下: “0.1111、0.1111”或其他

file_in = open('foo.dat', 'r')
for y in file_in.readlines()[0]:
    x.append(float(y))

我想你是这样的: “0.1111、0.1111”或其他

file_in = open('foo.dat', 'r')
for y in file_in.readlines()[0]:
    x.append(float(y))

这种方法怎么样:

x = []
with open('foo.dat', 'r') as f:
    for line in f:
        if line: #avoid blank lines
            x.append(float(line.strip()))
或:

最后,更紧凑:

with open('foo.dat', 'r') as f:
    x = [float(line.strip()) for line in lines if line]

这样,您就不必担心空行,您可以从
string
正确地转换为
float

这种方法如何:

x = []
with open('foo.dat', 'r') as f:
    for line in f:
        if line: #avoid blank lines
            x.append(float(line.strip()))
或:

最后,更紧凑:

with open('foo.dat', 'r') as f:
    x = [float(line.strip()) for line in lines if line]

这样,您就不必担心空行,您可以从
string
正确地转换为
float

您可以使用一个函数来确定正在解析的字符串是否为数字。基于此问题,您可以这样做:

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

x = []
file_in = open('filename.dat', 'r')
for y in file_in.read().split('\n'):
    if is_number(y):
        x.append(float(y))
file_in.close()

您可以使用函数来确定正在解析的字符串是否为数字。基于此问题,您可以这样做:

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

x = []
file_in = open('filename.dat', 'r')
for y in file_in.read().split('\n'):
    if is_number(y):
        x.append(float(y))
file_in.close()
你可以用这种方式

注意:reedline()是一个字符串,reedlines()是一个列表

file_in = open('foo.dat', "r")
r  =  file_in.readlines()
file_in.close()
l = 0
x = []
while l < len(r) :
    floating = float(r[l])
    x.append(floating)
    l += 1
file\u in=open('foo.dat',“r”)
r=文件_in.readlines()
文件_in.close()
l=0
x=[]
当l
您可以这样使用

注意:reedline()是一个字符串,reedlines()是一个列表

file_in = open('foo.dat', "r")
r  =  file_in.readlines()
file_in.close()
l = 0
x = []
while l < len(r) :
    floating = float(r[l])
    x.append(floating)
    l += 1
file\u in=open('foo.dat',“r”)
r=文件_in.readlines()
文件_in.close()
l=0
x=[]
当l
文件末尾是否有空行?您应该在
x.append(float(y))
行之前打印(y)
以查看无法转换的值。为什么
拆分('\n')
。。。让它
split()
行以查看无法转换的值。为什么要拆分('\n')
。。。让它
split()!消除
None
或空字符串也可以说
,如果y:
附加(float(y))
@martineau非常同意!消除
None
或空字符串