Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read lines from a file in python starting from the end

Tags:

python

file-io

I need to know how to read lines from a file in python so that I read the last line first and continue in that fashion until the cursor reach's the beginning of the file. Any idea's?

like image 486
Richard Avatar asked Aug 25 '10 17:08

Richard


People also ask

How do I read the first and last line of a file in Python?

Use file. readline() to read a single line from a file readline() to get the first line of the file and store this in a variable first_line . Create a second variable, last_line , and iterate through all lines in the file until the end. Once the iteration ends, last_line will contain the last line of the file.

How do I read a specific part of a file in Python?

Method 1: fileobject.readlines() A file object can be created in Python and then readlines() method can be invoked on this object to read lines into a stream. This method is preferred when a single line or a range of lines from a file needs to be accessed simultaneously.


1 Answers

Recipe 120686: Read a text file backwards (Python)

like image 157
Peter Avatar answered Oct 23 '22 16:10

Peter