简体   繁体   中英

Python - formatting a file.write string with spaces

I have a program and reads from a .txt file that I have created using another python code. I'm having trouble finishing this one.

It needs to read the .txt and spit out the numbers in that file along with their sum. Here's what I've got so far:

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

I get the error msg:

ValueError: could not convert string to float: '11 13 11 7 7'

Now, try this:

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

Because line is one line, and that is '11 13 11 7 7' .

So float() can't convert one string like that to float. And these codes use split() to split that string to a list like ['11', '13', '11', '7', '7'] . Then use for to extract it.

And now, float() can convert '11' , '13' , etc. to float.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM