I am appending to a file in my Python code and reading the file again at a different time.
Example:
if not os.path.isfile(f'./test.rpt'):
with open('test.rpt', 'a') as f:
f.write(f'some string')
The size of this appended file can be millions of lines and I was only interested in the last line, so I am reading the file in binary mode so I can go to the last line as follows: Also, the last line is always 11 characters, thus the -12
.
with open('test.rpt', 'rb') as f:
f.seek(-12, 2)
line = f.readline().decode("utf-8")
last_line = line.rstrip('\n')
print(f'Last line is: {last_line}')
But looks like my last line is always a new line. I am in read mode and still the last line looks to be a new line (as per the code, shouldn't the last line be 'some string'
?). How can I avoid reading the new line here and read the last line that I had written to the file which was 'some string'
.
When I manually open the file and write 'some string'
to it, I am able to read it correctly when I read the file again using above code. It's an issue just when my script appends to the file. That makes me wonder if the write()
function adds a new line character at the end of the file and if there is a way to avoid it? Or reading the second last line?