coder_3476
coder_3476

Reputation: 113

Append and read last line of file

Is there a way to append to a file and read it with the same "open" file command in Python3.7? I mean I do not want to have two open statements, one for open("//", "a") and one for open("//", "r"). What I am trying to achieve is run a script which appends the output to the file, and then read the last line of the file. "a+" does not help; it gives a index of out range for readlines()[-1].

Thanks in advance.

Upvotes: 1

Views: 1251

Answers (1)

blhsing
blhsing

Reputation: 106513

Opening the file in a+ makes the file pointer point to the end of the file, which makes it hard to read the last line. You can instead open the file in r+ mode, iterate over the file object until you obtain the last line, and then append the additional output to the file:

with open('file', 'r+') as file:
    for line in file:
        pass
    file.write(output)

# variable line now holds the last line
# and the file now has the content of output at the end

Upvotes: 2

Related Questions