I need to read data from a file game.txt and append the data into two lists. The first list should hold the player's name and the second list should hold the high score.
Also, this is for school and I'm not allowed to use split method, dictionaries, or with statements.
The game.txt file is a list of names and scores that looks like this:
John\n
7\n
Mary\n
5\n
Larry\n
9\n
Mark\n
4\n
def read_file():
infile = open(FILENAME, 'r')
line = infile.readline().rstrip('\n')
while line != '':
for item in FILENAME:
player_names.append(line)
high_scores.append(line)
line = infile.readline().rstrip('\n')
infile.close()
You can read two lines at a time, and store them as the name and score.
def parse_scores(filename):
player_names = []
high_scores = []
file = open(filename, "r")
try:
while (
name := file.readline().strip()
) and (
score := file.readline().strip()
):
player_names.append(name)
high_scores.append(int(score))
finally:
file.close()
return player_names, high_scores
def main():
player_names, high_scores = parse_scores("game.txt")
print("Player Names:", player_names)
print("High Scores:", high_scores)
if __name__ == "__main__":
main()
This assumes that game.txt
is in the following format:
John
7
Mary
5
Larry
9
Mark
4
The program output should be:
Player Names: ['John', 'Mary', 'Larry', 'Mark']
High Scores: [7, 5, 9, 4]
The more pythonic or idiomatic alternative would be to use splitlines()
and then take alternating slices.
def parse_scores(filename):
with open(filename, "r") as file:
lines = file.read().splitlines()
player_names = lines[::2]
high_scores = list(map(int, lines[1::2]))
return player_names, high_scores
def main():
player_names, high_scores = parse_scores("game.txt")
print(f"Player Names: {player_names}")
print(f"High Scores: {high_scores}")
if __name__ == "__main__":
main()