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

标签 python

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

相关文章:

python - Keras 模型给出的测试精度为 1.0

Python 列表变成字典?

python - 如何在 Python 中使用 for 循环从 0 迭代到 sys.maxint

python - 当 tkinter 窗口关闭时,python 程序并未结束

python - 如果第一次调用卡住,如何在 Python 中的 urllib2.urlopen 中发送重复请求?

python - 使用 Python 进行组合词匹配的正则表达式

python - 如何修复 "' str' object does not support item assignment"在 MongoDb 中的错误?

python - 运行时错误 : cannot access configuration outside request

python - 函数调用中的双括号是什么意思?例如函数(foo)(酒吧)

python - 快速半正弦逼近(Python/Pandas)