gpt4 book ai didi

Python/函数参数

转载 作者:太空宇宙 更新时间:2023-11-04 09:14:59 26 4
gpt4 key购买 nike

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

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

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

最佳答案

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

哦,你应该停止在 try block 中放入不必要的代码。干净的解决方案如下所示:

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

关于Python/函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10808162/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com