I'm sure I'm missing something obvious and probably asked before but I can't seem to get the right combination of keywords together to give me an answer.
How can I write out the first n lines of a file (in effect, the opposite of file.readlines()[0:10]
)?
e.g. I have a function that takes in an input file, and needs to process information from the latter part, throwing out a header. However I want to keep the multi-line header, to be put back in to an output file.
def readInfile(infile):
with open(infile, 'r') as ifh:
# Skip exta info at top of file
header = ifh.readline()[0:10] # Keep the header for later?
noheader = ifh.readlines()[11:]
for line in noheader:
# Do the useful stuff
usefulstuff = foo()
return usefulstuff, header
Then later I want to write out in the format of the input file, using their header:
print(header)
for thing in usefulstuff:
print(thing)
Is there a method I'm missing, or is readlines
no good for this as it returns a list?
I assumed
for line in header:
print(line)
would work, but it doesn't seem to in this case - so I must be doing something wrong?
EDIT
Why does trying to use readlines()[]
twice fail for the second range?
I fixed the code as @pbuck pointed out, that the header line should have been readlines()
not readline
but now the noheader
variable is empty? Do I really have to open the file twice?!
Literally, read first n lines, then stop.
def read_first_lines(filename, limit):
result = []
with open(filename, 'r') as input_file:
# files are iterable, you can have a for-loop over a file.
for line_number, line in enumerate(input_file):
if line_number > limit: # line_number starts at 0.
break
result.append(line)
return result