2012-05-29 103 views
1

主要目标: 函数从文本文件中读取最高分数。 要传递到函数的参数: 文本文档!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 

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

+2

你想传递一个路径字符串,并有此功能打开文件,或者你想传递一个文件对象,并有该功能操作? – dcolish

+2

我真的不明白如何能够编写现有的代码并让它工作,而不必自己回答问题。 –

回答

4
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 
+1

我试图添加文件名,例如:def highscore(data.txt),但它不起作用,有一个碰撞的syntexerror。 – Geostigmata

+0

我不喜欢'如果不是os.path.isfile()'构造,因为它要求权限而不是原谅。如果该文件在调用成功和随后的'with open()'行之间被删除,该怎么办?我更喜欢你最后的例子。 –

+0

@Geostigmata不要在你的文件的参数名称中加上'.'(句号)。因此,不是'data.txt',而是尝试'data_txt',或者更好的是'filename',因为我们的答案都显示。 – Levon

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

只需添加一个变量标识符(例如, filename)添加到您的参数列表中,然后在打开文件时参考它。

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

topscore = highscore("topscore.txt") 
1

另一种选择是提供关键字参数。例如,如果您有使用此功能的旧代码,并且出于某种奇怪的原因无法更新,这可能很有用。关键字参数可以包含默认值。

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

然后你就可以调用这个函数像以前一样使用默认值, “FILENAME.TXT”:

highscore() 

或指定任何新的文件名:

highscore(filename = "otherfile.csv") 

见蟒蛇文档以获取更多信息。 http://docs.python.org/tutorial/controlflow.html#default-argument-values