Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a Line From File Without Advancing [Pythonic Approach]

Tags:

python

What's a pythonic approach for reading a line from a file but not advancing where you are in the file?

For example, if you have a file of

cat1 cat2 cat3 

and you do file.readline() you will get cat1\n . The next file.readline() will return cat2\n .

Is there some functionality like file.some_function_here_nextline() to get cat1\n then you can later do file.readline() and get back cat1\n?

like image 482
user1431282 Avatar asked May 30 '13 15:05

user1431282


People also ask

How do you read a single line from a file in Python?

The readline() method returns one line from the file. You can also specified how many bytes from the line to return, by using the size parameter.

Which function is used to read single line from file?

Which function is used to read single line from file? content = fh. readline().

How do you read the content of a file line by line in Python?

Method 1: Read a File Line by Line using readlines() readlines() is used to read all the lines at a single go and then return them as each line a string element in a list. This function can be used for small files, as it reads the whole file content to the memory, then split it into separate lines.

When reading a file using the file object what method is best for reading the entire file into a single string?

The readlines method returns the contents of the entire file as a list of strings, where each item in the list represents one line of the file. It is also possible to read the entire file into a single string with read .


1 Answers

As far as I know, there's no builtin functionality for this, but such a function is easy to write, since most Python file objects support seek and tell methods for jumping around within a file. So, the process is very simple:

  • Find the current position within the file using tell.
  • Perform a read (or write) operation of some kind.
  • seek back to the previous file pointer.

This allows you to do nice things like read a chunk of data from the file, analyze it, and then potentially overwrite it with different data. A simple wrapper for the functionality might look like:

def peek_line(f):     pos = f.tell()     line = f.readline()     f.seek(pos)     return line  print peek_line(f) # cat1 print peek_line(f) # cat1 

You could implement the same thing for other read methods just as easily. For instance, implementing the same thing for file.read:

def peek(f, length=1):     pos = f.tell()     data = f.read(length) # Might try/except this line, and finally: f.seek(pos)     f.seek(pos)     return data  print peek(f, 4) # cat1 print peek(f, 4) # cat1 
like image 165
Henry Keiter Avatar answered Sep 24 '22 16:09

Henry Keiter