Python 浮点数必须是字符串还是数字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30531766/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:36:30  来源:igfitidea点击:

Float must be a string or a number?

pythontype-conversiontext-files

提问by Pancake_Senpai

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:

文本文件 money.txt 仅包含以下内容:

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.

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

采纳答案by tobias_k

moneyis a fileobject, notthe content of the file. To get the content, you have to readthe file. If the entire file contains just that one number, then read()is all you need.

money是一个file对象而不是文件的内容。要获取内容,您必须访问read文件。如果整个文件只包含那个数字,那么read()您所需要的就足够了。

moneyx = float(money.read())

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

否则,您可能希望使用readline()读取一行,甚至尝试使用csv模块来读取更复杂的文件。

Also, don't forget to close()the file when you are done, or use the withkeyword to have it closed automatically.

另外,完成后不要忘记close()打开文件,或使用with关键字使其自动关闭。

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

回答by heinst

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 是一个文件,而不是一个字符串,因此您不能将整个文件转换为浮点数。相反,您可以执行类似的操作,将整个文件读入一个列表,其中每一行都是列表中的一个项目。你会循环并以这种方式转换它。

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

回答by itzhaki

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

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

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