[Python] Remove all empty lines at the end of file [duplicate]

Discussão em 'Python' iniciado por Stack, Fevereiro 26, 2025.

  1. Stack

    Stack Membro Participativo

    Let’s say I have an input .txt file with the following contents:

    a
    b

    c
    d

    # this line is empty
    # this one too
    # and this one


    How can I truncate the .txt file at d, assuming that I DON’T want to remove empty lines between the start of file and the last non-empty line (like the ones between b and c)?

    The reason why I’d want to do such a thing is because the end of file needs to follow a given format and I need to make sure all empty lines are removed before using f.write() to insert that format.

    Continue reading...

Compartilhe esta Página