2015-11-05 65 views
2

我已經定義了2個列表,並且我想將文本文件的內容讀入下面顯示的2個列表中。我無法弄清楚如何構造代碼,以便將文本文件中的名稱和數字調用到列表中?獲取文件名並將該文件的內容讀入2個列表

def read_file(filename, player_names, player_scores): 

    infile = open("high_scores.txt", "r") 

    infile.close() 

定義的列表

player_names = ["","","","",""] 
player_scores = [0,0,0,0,0] 
print('Player_names',player_names) 
print('Player_scores',player_scores) 
+2

什麼是你的文本文件的結構?另外,嘗試多一點。你還沒有嘗試過任何東西。 – Abhineet

+0

該文件是什麼樣子? –

+0

蘭斯威廉姆斯10 福斯特福斯特8 菲爾默裏6 傑克遜雷丁1 – basketball5

回答

1

考慮你的輸入文件是分隔的球員和得分

PLAYER1 100

player2 50

player3 65

0標籤

你的工作代碼將是

def read_file(filename, player_names, player_scores): 
    with open(filename, "r") as infile: 
     for line in infile: 
      player_score = line.split('\t') 
      player_names.append(player_score[0]) 
      player_scores.append(int(player_score[1])) 


if __name__ == "__main__": 
    player_names = [] 
    player_scores = [] 
    read_file('high_scores.txt', player_names, player_scores) 
    print('Player_names',player_names) 
    print('Player_scores',player_scores) 

,這將是您的輸出:

( 'Player_names',[ 'PLAYER1', 'player2', 'player3'])

( 'Player_scores',[100,50,65])

+0

謝謝,非常感謝 – basketball5

相關問題