Python/函数参数

2024-05-17 12:13:26 发布

您现在位置:Python中文网/ 问答频道 /正文

主要目标: 函数从文本文件中读取最高分数。 要传递到函数的参数: 文本文档!

def highscore():
    try:
        text_file = open ("topscore.txt", "r")
        topscore = int(text_file.read())
        print topscore
        text_file.close()
        return topscore
    except:
        print "Error - no file"
        topscore = 0
        return topscore

如何添加文本文件作为参数?


Tags: 函数text目标参数returndef文本文档open
3条回答
def highscore(filename):
   try:
      text_file = open(filename, "r")
      ...

只需将变量标识符(例如filename)添加到参数列表中,然后在打开文件时引用它。

然后用您选择的文件名调用您的函数。

topscore = highscore("topscore.txt")

另一个选项是提供关键字参数。例如,如果您有使用此函数的旧代码,并且由于某种奇怪的原因无法更新,那么这可能非常有用。关键字参数可以包含默认值。

def highscore( filename = "filename.txt" ):
    try:
        text_file = open (filename, "r")

然后可以像以前一样调用此函数以使用默认值“filename.txt”:

highscore()

或指定任何新文件名:

highscore( filename = "otherfile.csv" )

有关更多信息,请参阅python文档。 http://docs.python.org/tutorial/controlflow.html#default-argument-values

def highscore(filename):
    try:
        text_file = open (filename, "r")

哦,您应该停止在try块中放入多余的代码。一个干净的解决方案如下:

def highscore(filename):
    if not os.path.isfile(filename):
        return 0
    with open(filename, 'r') as f:
        return int(f.read())

或者,如果您希望在读取文件失败的任何情况下返回0:

def highscore(filename):
    try:
        with open(filename, 'r') as f:
            return int(f.read())
    except:
        return 0

相关问题 更多 >