Read the last line from the file.
First option. Simplest. But the file must fit entirely into memory. In the case of an empty file does not work correctly.
with open('test.txt') as file: last_line = file.readlines()[-1].strip()
(We read all the lines of the file in the list, take the last one, remove the newline character, if it exists.)
The second option. A little harder. But does not require memory to store the entire file. In the case of an empty file also works incorrectly.
with open('test.txt') as file: for last_line in file: pass last_line = last_line.strip()
(We read the file line by line. In the variable, the last read line is saved. Then again, we delete the newline character, if there is one.)
The third option. It is similar to the first, but it works correctly in the case of an empty file. In this case, the last_line will contain the value None .
last_line = None with open('test.txt') as file: lines = file.readlines() if lines: last_line = lines[-1].strip()
Fourth option. It is similar to the second, but it works correctly in the case of an empty file. In this case, the last_line will contain the value None .
last_line = None with open('test.txt') as file: for last_line in file: pass if last_line: last_line = last_line.strip()