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.
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With