How do I read the first line of a file twice?
I have large files with many lines and you want to read the first line first and then skip all lines again starting from the first line.
At first I thought that something like this would do:
file = open("fileName", 'r')
first_line = file.readline()
DoStuff_1(first_line)
for line in file:
DoStuff_2(line)
file.close()
But the problem with this script is that the first line that is passed to DoStuff_2
is the second line, not the first. I don't have a good intuition as to what kind of object file
. I think this is an iterator and have no idea how to deal with it. Bad solution I found,
file = open("fileName", 'r')
first_line = file.readline()
count = 0
for line in file:
if count == 0:
count = 1
DoStuff_1(first_line)
DoStuff_2(line)
file.close()
But it's pretty dumb and is a little expensive to compute as it runs an if statement on every iteration.
source to share
I would like to use a generator to abstract the general control flow. Something like:
def first_and_file(file_obj):
"""
:type file_obj: file
:rtype: (str, __generator[str])
"""
first_line = next(file_obj)
def gen_rest():
yield first_line
yield from file_obj
return first_line, gen_rest()
In Python 2.7, replace yield from
with:
for line in file_obj:
yield line
source to share