Search code examples
pythonnumberstext-files

File reading only first digit of a number rather than the whole number


The problem is that i have a text file with each line being PlayerName wins with x points with each player name and number being different and obviously with them being different are different number if digits long Problem is as a part of the code it needs to read the entire code and print the players with the top 5 scores as such.

TOP 5 ALL TIME SCORES

Martin wins with 123 points

Jamie wins with 54 points

Kyle wins with 43 points

Andrew wins with 32 points

Dylan wins with 21 points

(The full code is a dice game with random rolling and a gambling system and tiebreaker but im at my dads house right now so dont have access to the full code)

`





name = str(input("Player 1 name"))
name2 = str(input("Player 2 name"))
score = str(input("Player 1 score"))
score2 = str(input("Player 2 score"))
text_file = open("CH30.txt", "r+")
if score > score2:
    content = text_file.readlines(30)
    if len(content) > 0 :
        text_file.write("\n")
    text_file.write(name)
    text_file.write (" wins with ")
    text_file.write (score)
    text_file.write (" points")
else:
    content = text_file.readlines(30)
    if len(content) > 0 :
        text_file.write("\n")
    text_file.write (name2)
    text_file.write (" wins with ")
    text_file.write (score2)
    text_file.write (" points")


text_file = open('CH30.txt.', 'r')
Lines = text_file.readlines()
PlayersScores = []

# read each line get the player name and points 
for line in Lines:
    # split the line into list of strings
    line = line.split(" ")
    # removing \n from last element
    line[-1] = line[-1].replace("\n", "")
    print(line)
    # find player name position
    playerName = line.index("wins") - 1
    # find points position
    points = line.index("points") - 1
    points = int(points)
    # add the tuple (playerName, points) in a list
    PlayersScores.append((line[playerName], line[points]))
# descending order sort by player score
PlayersScores = sorted(PlayersScores, key=lambda t: t[1], reverse=True)

# get the first 5 players
print("Highest Scores:\n")
for i in range(5):
    print(str(i+1) + ". " + PlayersScores[i][0] + " " + PlayersScores[i][1] + " points")


` the output for this is

Jamie wins with 54 points

Kyle wins with 43 points

Andrew wins with 32 points

Dylan wins with 21 points

Martin wins with 123 points

note The names shown are just an example actually it reads from a text file (CH30.txt) rather than just 5 preselected names

Any help greatly appreciated Thanks


Solution

  • Below is the fixed part of the code to get the correct value for points. I did not touch the other parts of the code.

    text_file = open('CH30.txt.', 'r')
    Lines = text_file.readlines()
    PlayersScores = []
    for line in Lines:
        line = line.split()
        playerName = line[0]
        points = int(line[3])
        .....