python - How to read first line of a file twice? -
i have big files many lines , want read first line first , loop through lines starting first line again.
i first thought it:
file = open("filename", 'r') first_line = file.readline() dostuff_1(first_line) line in file: dostuff_2(line) file.close()
but issue script first line passed dostuff_2
second line , not first one. don't have intuition of kind of object file
is. think iterator , don't know how deal it. bad solution found
file = open("filename", 'r') first_line = file.readline() count = 0 line in file: if count == 0: count = 1 dostuff_1(first_line) dostuff_2(line) file.close()
but pretty dumb , computationally bit costly runs if statement @ each iteration.
you this:
with open('filename', 'r') file: first_line = file.readline() dostuff_1(first_line) dostuff_2(first_line) # remaining lines line in file: dostuff_2(line)
note changed code use with
file
automatically closed.
Comments
Post a Comment