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
?
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? content = fh. readline().
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.
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 .
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:
tell
.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With