Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - formatting a file.write string with spaces

Tags:

python

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'
like image 479
Caitlin G Avatar asked Aug 23 '26 10:08

Caitlin G


2 Answers

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.

like image 50
Remi Crystal Avatar answered Aug 26 '26 00:08

Remi Crystal


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()
like image 24
Jason Avatar answered Aug 25 '26 22:08

Jason



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!