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

时间:2015-09-19 01:10:34

标签: python

我有一个程序,并从我使用另一个python代码创建的.txt文件中读取。我在完成这个问题时遇到了麻烦。

它需要读取.txt并吐出该文件中的数字及其总和。这是我到目前为止所得到的:

myExpandableListAdapter = new MyExpandableListAdapter(Hotel.this.getActivity().getApplicationContext(), groupList, childMap);

我收到错误消息:

 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()

2 个答案:

答案 0 :(得分:5)

现在,试试这个:

 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'等转换为浮动。

答案 1 :(得分:2)

import random

def main():
    myfile = open('numbers.txt', 'w')
    total = 0
    for count in range(3,8):
        file_size = random.choice(range(5,19,2))
        myfile.write(format(str(file_size) + ' '))
        total += file_size
    myfile.write(format(total))
    myfile.close()
main()