2014-10-06 41 views
0

所以我有一個玩家輸入他/她的名字。該名稱被寫入一個文件。然後打開文件,讀取並將全局變量更改爲所述文件中的內容。這最終會成爲我爲一個班級開發的遊戲的一個保存功能。.txt閱讀以改變全球變數

def nameWrite(): 
    text_file = open("name.txt", "w+") 
    print('what u name') 
    text_file.write(input()) 
    text_file.close() 

def nameRead(): 
    text_file = open("name.txt","r") 
    print ("This is the output in file:",text_file.read()) 
    global playerName 
    playerName = text_file.read() 
    text_file.close() 

nameWrite() 
nameRead() 
print("You name is now:",playerName) 

這爲什麼不改變變量playerName

+0

最新錯誤? – smushi 2014-10-06 23:14:36

+0

全局變量未更新 – 2014-10-06 23:16:39

+2

代碼看起來像可以工作,有什麼問題?我不太喜歡使用'global';最好只是讓'nameRead()'函數'返回playerName'。 – 2014-10-06 23:18:58

回答

0

全局變量更新,只是沒有更新到你認爲它應該。

看看這個代碼:

def nameRead(): 
    text_file = open("name.txt","r")       # 1 
    print ("This is the output in file:",text_file.read()) # 2 
    global playerName 
    playerName = text_file.read()       # 3 
    text_file.close() 

當執行,這是發生了什麼:

  1. 文件被打開
  2. 所有文件中的數據被讀取,並且文件指針移動到文件尾部
  3. 下次您閱讀時,不會再讀取所需的數據,因此playerName是空字符串

除非您關閉並重新打開文件,否則您不能從文件讀取兩次,或使用seek函數將文件指針移回開頭。