2012-05-29 100 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