Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 709
Pancake_Senpai Avatar asked May 29 '15 14:05

Pancake_Senpai


2 Answers

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)
like image 145
tobias_k Avatar answered Oct 17 '22 00:10

tobias_k


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)
like image 33
heinst Avatar answered Oct 17 '22 01:10

heinst