打开txt文件,float()的文字无效

时间:2016-06-22 14:13:49

标签: python

只是尝试以txt格式打开此数据集。

400.,41.7693
403.977686150861,42.68129270405837
408.3434392432695,43.86688321933424
412.61217560029104,45.59966935704514
416.4928450157652,48.72324436844505
420.9556148435605,51.64162102143182
423.86611690516617,53.534005882352936
427.0676691729323,56.2927838121295
431.43342226534077,59.73555626994983
435.31409168081495,60.85274733242134
439.291777831676,64.52351796625626
442.68736357021584,67.25949607843137
446.56803298569,68.92388276333789
450.73975260732476,71.29506379388965
454.7174387581858,72.41225485636114
458.21004123211253,73.68904464204286
462.4787775891341,75.5130300501596
466.6504972107689,76.72142038303693
470.2401164200825,77.72461235750114
473.73271889400917,78.63660506155951
477.61338830948335,79.57139758321932
481.9791414018918,80.64298901048792

试图打开...

with open('SunData.txt') as I:
    data = I.read()
data = data.split('\n')
WaveData = [float(row.split()[0]) for row in data]
IntData = [float(row.split()[1]) for row in data]

我已经回复了这个错误,

invalid literal for float(): 400.,41.7693

如何更正此错误?

4 个答案:

答案 0 :(得分:4)

使用row.split(',')分隔逗号。没有传递参数的.split()只会在空格上分开。

答案 1 :(得分:1)

for item in data.split('\n'):
    floats = item.split(',')

答案 2 :(得分:0)

这并没有做任何事情:

row.split()

也许你的意思是

row.split(',')

答案 3 :(得分:0)

如果要读取txt文件,可以使用numpy库和命令:np.loadtxt()

然后你可以制作大量的进程,因为你得到一个numpy数组;)

import numpy as np

reading = np.loadtxt("SunData.txt", delimiter=',', usecols=(0, 1), unpack=True)

print reading

enter image description here

文档在那里:doc