所以我定义了这些:
def highscorenumber():
file = open('GUESS THE NUMBER HIGHSCORE NUMBER.txt', 'r')
highscorenum = file.readline(1)
def highscorename():
file = open('GUESS THE NUMBER HIGHSCORE NAME.txt', 'r')
highscorenum = file.readline(1)
并且这些都保存在与程序相同的目录中。 “GUESS THE NUMBER HIGHSCORE NUMBER.txt”
打开时显示:“1”
并且“GUESS THE NUMBER HIGHSCORE NAME.txt”
打开时显示“max”
。
但是当我运行时:
print("The current highscore is",highscorenumber,"set by",highscorename)
它说:
The current highscore is <function highscorenumber at 0x0000000002D46730> set by <function highscorename at 0x0000000001F67730>
为什么它这么说而不是“当前最高分是 1 由 max 设置”
?
最佳答案
因为您没有调用函数,Python 正在打印函数对象本身的表示:
>>> def f():
... return 1
...
>>> print(f)
<function f at 0x015E1618>
>>> print(f())
1
>>>
如上所述,您需要调用函数才能打印它们的返回值:
print("The current highscore is",highscorenumber(),"set by",highscorename())
<小时/>
您还应该从每个函数返回对 readline
的调用:
def highscorenumber():
file = open('GUESS THE NUMBER HIGHSCORE NUMBER.txt', 'r')
return file.readline(1)
否则,函数将默认返回None
。
最后,我将使用 with 语句打开文件:
def highscorenumber():
with open('GUESS THE NUMBER HIGHSCORE NUMBER.txt', 'r') as file:
return file.readline(1)
这将确保它们在您使用完后关闭。
关于python - 读取 python 文件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27431410/