python - 读取 python 文件时出错

标签 python file function

所以我定义了这些:

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/

相关文章:

multithreading - 使用函数 + 偏移量获取模块名称

matlab - 是否可以在 MatLab 的脚本中定义局部函数?

Python shell 脚本

python - 在 python 中对两个 { } 使用 re.split()

html - 如何在移动设备上测试 PC 上的 HTML/CSS 文件

java - 从 Java 文本文件中删除特定行?

python - 使用 pyparsing 匹配非空行

python - 使用 python 的 csv.writer 生成标题行

python - 使用 python 更改视频文件属性

c - 如何修改已传递给 C 函数的指针?