Pancake_Senpai
Pancake_Senpai

Reputation: 945

Float must be a string or a number?

I have a very simple program. The code:

money = open("money.txt", "r")
moneyx = float(money)
print(moneyx)

The text file, money.txt, contains only this:

0.00

The error message I receive is:

TypeError: float() argument must be a string or a number

It is most likely a simple mistake. Any advice? I am using Python 3.3.3.

Upvotes: 11

Views: 54392

Answers (3)

tobias_k
tobias_k

Reputation: 82929

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, don't 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)

Upvotes: 12

itzhaki
itzhaki

Reputation: 840

It's 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)

Upvotes: 0

heinst
heinst

Reputation: 8786

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)

Upvotes: 4

Related Questions