Reputation: 23
I have defined 2 lists and I want to read the contents of a text file into the 2 lists shown below. I can't work out how to structure the code so that the names and numbers from the text file are called into the lists?
def read_file(filename, player_names, player_scores):
infile = open("high_scores.txt", "r")
infile.close()
defined lists
player_names = ["","","","",""]
player_scores = [0,0,0,0,0]
print('Player_names',player_names)
print('Player_scores',player_scores)
Upvotes: 2
Views: 218
Reputation: 10931
Consider your input file is a tab delimited of players and scores
player1 100
player2 50
player3 65
your working code will be
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)
and this will be your output:
('Player_names', ['player1', 'player2', 'player3'])
('Player_scores', [100, 50, 65])
Upvotes: 1