Python go to last line of file
Skip to content. Change Language. Related Articles. Table of Contents. Improve Article. Save Article. Like Article. Python implementation to. LastNlines fname, N. When ''. This fixes that. HOW TO? If reading the whole file is acceptable then use a deque. Top 3 video Explaining python - Get last n lines of a file, similar to tail. Does Python have a ternary conditional operator? In order to seek the end of file, we have to open the file in binary mode. We seek to the last 2 characters since the file is likely to end with a newline.
Then, keep reading a single byte until a newline character is found. And, finally, we use readline to read the final line, and decode to convert from bytes to string. Xuan Ngo is the founder of OpenWritings. He currently lives in Montreal, Canada. The file. We can then get the last line of the file by referencing the last index of the list using -1 as an index.
We used [-1] because the readlines function returns all the lines in the form of a list, and this [-1] index gives us the last element of that list.
0コメント