python – Float must be a string or a number?

python – Float must be a string or a number?

money is a file object, not the content of the file. To get the content, you have to read the file. If the entire file contains just that one number, then read() is all you need.

moneyx = float(money.read())

Otherwise you might want to use readline() to read a single line or even try the csv module for more complex files.

Also, dont forget to close() the file when you are done, or use the with keyword to have it closed automatically.

with open(money.txt) as money:
    moneyx = float(money.read())
print(moneyx)

Money is a file, not a string, therefore you cannot convert a whole file to a float. Instead you can do something like this, where you read the whole file into a list, where each line is an item in the list. You would loop through and convert it that way.

money = open(money.txt, r)
lines = money.readlines()
for l in lines:
   moneyx = float(l)
   print(moneyx)

python – Float must be a string or a number?

Its better practice to use with when opening a file in python. This way the file is implicitly closed after the operation is done

with open(money.txt, r) as f:
    content = f.readlines()
    for line in content:
        print float(line)

Leave a Reply

Your email address will not be published.