Reading the last line of an empty file on python

Question:

I have this function on my code that is supposed to read a files last line, and if there is no file create one. My issue is when it creates the files and tries to read the last line it comes up as an error.

with open(HIGH_SCORES_FILE_PATH, "w+") as file:
        last_line = file.readlines()[-1]
        if last_line == 'n':
            with open(HIGH_SCORES_FILE_PATH, 'a') as file:
                file.write('Jogo:')
                file.write('n')
                file.write(str(0))
                file.write('n') 

I have tried multiple ways of reading the last line but all of the ones I’ve tried ends in an error.

Asked By: migas_silverio

||

Answers:

Opening a file in "w+" erases any content in the file. readlines() returns an empty list and trying to get value results in an IndexError. You can test for a file’s existence with os.path.exists or os.path.isfile, or you could use an exception handler to deal with that case.

Start with last_line set to a sentinel value. If the open fails, or if no lines are read, last_line will not be updated and you can base file creation on that.

last_line = None
try:
    with open(HIGH_SCORES_FILE_PATH) as file:
        for last_line in file:
            pass 
except OSError:
    pass

if last_line is None:
    with open(HIGH_SCORES_FILE_PATH, "w") as file:
        file.write('Jogo:n0n')
    last_line = '0n'
Answered By: tdelaney

To read the last line of a file, you can use the seek method and set the position to the beginning of the file, then move the file cursor to the end of the file. Then, you can use the readline method to read the last line.

with open(HIGH_SCORES_FILE_PATH, "w+") as file:
    file.seek(0, 2)  # Move cursor to the end of the file
    last_line = file.readline()
    if last_line == 'n':
        with open(HIGH_SCORES_FILE_PATH, 'a') as file:
            file.write('Jogo:')
            file.write('n')
            file.write(str(0))
            file.write('n')

Note that if the file is empty, readline will return an empty string, so you should check for that case as well.

with open(HIGH_SCORES_FILE_PATH, "w+") as file:
    file.seek(0, 2)  # Move cursor to the end of the file
    last_line = file.readline()
    if last_line == '' or last_line == 'n':
        with open(HIGH_SCORES_FILE_PATH, 'a') as file:
            file.write('Jogo:')
            file.write('n')
            file.write(str(0))
            file.write('n')
Answered By: Cyzanfar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.