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.

+3


source to share


3 answers


You can do it:

with open('fileName', 'r') as file:
    first_line = file.readline()
    DoStuff_1(first_line)
    DoStuff_2(first_line)

    # remaining lines
    for line in file:
        DoStuff_2(line)

      



Please note that I changed my code to use with

so it file

automatically closes.

+5


source


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

      

+2


source


Another answer is to just open the file twice.

with open("file.txt", "r") as r:
    Do_Stuff1(r.readline())

with open("file.txt", "r") as r:
    for line in r:
        Do_Stuff2(line)

      

+1


source







All Articles