float 必须是字符串还是数字?

Float must be a string or a number?

我有一个非常简单的程序。代码:

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

文本文件 money.txt 仅包含:

0.00

我收到的错误信息是:

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

这很可能是一个简单的错误。有什么建议吗?我正在使用 Python 3.3.3.

Money 是一个文件,而不是字符串,因此您不能将整个文件转换为浮点数。相反,您可以这样做,将整个文件读入列表,其中每一行都是列表中的一个项目。您将循环遍历并以这种方式转换它。

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

在 python 中打开文件时最好使用 "with"。这样操作完成后隐式关闭文件

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

moneyfile 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() 是你所需要的。

moneyx = float(money.read())

否则你可能想使用 readline() to read a single line or even try the csv 模块来处理更复杂的文件。

此外,完成后不要忘记 close() 文件,或使用 with 关键字让它自动关闭。

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