Caitlin G
Caitlin G

Reputation: 75

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'

Upvotes: 3

Views: 1711

Answers (2)

Remi Guan
Remi Guan

Reputation: 22282

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.

Upvotes: 5

Jason
Jason

Reputation: 2743

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

Upvotes: 2

Related Questions