我有一个程序并从我使用另一个 python 代码创建的 .txt 文件中读取。我很难完成这个。
它需要读取 .txt 并吐出该文件中的数字及其总和。到目前为止,这是我得到的:
def main():
total = 0
myfile = open('numbers.txt', 'r')
for line in myfile:
amount = float(line)
total += amount
print('End of file')
print('Numbers in file add up to ', format(total, ',.1f'), end='')
myfile.close()
main()
我收到错误消息:
ValueError: could not convert string to float: '11 13 11 7 7'
最佳答案
现在,试试这个:
def main():
total = 0
with open('numbers.txt', 'r') as myfile:
for line in myfile:
for i in line.split():
amount = float(i)
total += amount
print(line.strip(), 'End of file')
print('Numbers in file add up to ', format(total, ',.1f'), end='')
print()
main()
因为line
是一行,也就是'11 13 11 7 7'
。
因此 float()
无法将这样的一个字符串转换为 float 。这些代码使用 split()
将该字符串拆分为一个列表,如 ['11', '13', '11', '7', '7']
.然后使用 for
来提取它。
现在,float()
可以将'11'
、'13'
等转换为 float 。
关于Python - 用空格格式化 file.write 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32663088/