[Python] From a .txt, how can I get the content of the line above a certain line

Discussão em 'Python' iniciado por Stack, Março 29, 2025.

  1. Stack

    Stack Membro Participativo

    I have a .txt file which includes the following:

    Karin
    3543
    Joe
    2354
    Bob
    2019


    I am able to find the maximum value of all integers and have the line in a variable, i, but the problem comes in when I try and find the contents of the line above the highest integer. For example, 3543 is the highest, so "Karin" would be stored in a variable. Any idea on how this would be done?

    with open("r.txt", 'r') as f:
    highestScore = 0
    highestPlayer = ""

    line_numbers = [1, 3, 5]

    for i, line in enumerate(f):
    if i in line_numbers:
    if int(line) > int(highestScore):
    highestScore = line

    elif i > 5: # number of lines in .txt file
    break

    print(highestPlayer, str(highestScore))

    Continue reading...

Compartilhe esta Página