ValueError:无法将字符串转换为浮点。

2024-06-09 13:10:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图读入文本文件并将输入转换为列表:

model = open('Grids/Dusty_AGN/Z'+Z+'_n'+n+'_alp-'+alpha+'_fluxes.txt','r')

Hafluxfile = model.readline() + model.readline() + model.readline() ; the first three lines of the file contain the values that I need

Haflux = []

Haflux.append([float(x) for x in Hafluxfile.split(' ')])

如果我print Hafluxfile,我看到的是:

^{pr2}$

{I>并尝试将此消息追加到cd2>时:

ValueError: could not convert string to float

不,除了冒号之外,没有什么是我没有包括的,它似乎在告诉我,空白阻止了它到达第一个数字?我不知道怎么解决这个问题。在


Tags: thealpha列表readlinemodelopenfloat文本文件
3条回答

首先,应该使用+连接路径组件,而应该使用^{}函数。既然这么说,我将使用^{}模块。在

import os
import csv

haflux = []
filename = os.path.join('Grids/Dusty_AGN/Z', Z, '_n', n, '_alp-', alpha, '_fluxes.txt')
with open('filename') as f:
    reader = csv.reader(f, delimiter=' ')
    for n in range(3):
        haflux.append([float(i) for i in next(reader) if i])

print(haflux)
#  [[2.975, 2.943, 2.927, 2.918, 2.907, 2.902], [2.893, 2.877, 2.867, 2.87, 2.899, 2.935], [2.919]]

问题是你得到了一些空元素。在

Haflux.append([float(str(x)) for x in Hafluxfile.split(' ') if len(x)>1])

这会照顾他们的。在

项目之间有多个空格。调用^{}时不要指定分隔符:

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

而且,看起来你还有前导空格和尾随空格,你可以用^{}来修剪:

[float(x) for x in Hafluxfile.strip().split()]

相关问题 更多 >