Python – 使用空格格式化file.write字符串

我有一个程序,并从我使用另一个
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()

因为线是一条线,那就是’11 13 11 7 7′.

所以float()不能将这样的字符串转换为float.这些代码使用split()将该字符串拆分为[’11’,’13’,’11’,’7′,’7’等列表.然后用它来提取它.

现在,float()可以将’11’,’13’等转换为float.

点赞