我有:
data1=open('file1.txt','r')
data2=open('file2.txt','w+')
for line in data1.readlines():
items = line.split(' ')
x = log(float(items[0]))
y = float(items[1])
data2.write(x)
data2.write('\t')
data2.write(y)
data2.write('\n')
其中file1包含
l 0.1
2 0.1
3 0.1
4 0.1
5 0.1
6 0.1
7 0.1
8 0.1
9 0.1
10 0.1
获取
ValueError: could not convert string to float: 1
我不太明白为什么我会收到错误,请帮助我。 提前谢谢。
答案 0 :(得分:1)
这是因为你的文件的第一行是字母l
,它不能转换为浮点数。也许这是一个错字,你希望它是数字1
?如果是这样,那么你的代码将是正确的。然后你需要进行其他更改,以使你的代码更像pythonic,就像使用with
来处理文件一样:
from math import log
txt = list()
with open('file1.txt', 'r') as fr, open('file2.txt', "w+") as fw:
for line in fr:
items = line.split()
txt.append("{0}\t{1}".format(items[0], log(float(items[1]))))
fw.write("\n".join(txt))
答案 1 :(得分:0)
jabaldonedo说,+ split(' ')
将大部分行拆分为多个项目的列表,而不仅仅是2,因为每行包含多个空格而不仅仅是一个。
例如:
>>> '2 0.1'.split(' ')
['2', '', '', '0.1']
所以items[1]
肯定不能满足你的需要。
快速解决方案是通过执行items
简单地获取items[-1]
的最后一个元素。但最好正确分裂(即使用正则表达式):
>>> import re
>>> re.split(' +', '2 0.1'.split(' '))
['2', '0.1']
或者,如果您不想使用正则表达式,那么另一个稍微不合理的解决方法就是:
>>> items = '2 0.1'.split(' ')
>>> items = [x for x in items if x]
>>> items
['2', '0.1']
注意:我正在使用交互式Python,以防您想知道>>>
前缀。
更新: '2 0.1'.split()
(即split()
没有参数)似乎做同样的工作;也就是说,它摆脱了多个空间。 (谢谢,@ hhwhsa)。