A Python program I\'m writing is to read a set number of lines from the top of a file, and the program needs to preserve this header for future use. Currently, I\'m doing s
import itertools
header_lines = list(itertools.islice(file_handle, header_len))
# or
header = "".join(itertools.islice(file_handle, header_len))
Note that with the first, the newline chars will still be present, to strip them:
header_lines = list(n.rstrip("\n")
for n in itertools.islice(file_handle, header_len))
s=""
f=open("file")
for n,line in enumerate(f):
if n<=3 : s=s+line
else:
# do something here to process the rest of the lines
print s
f.close()
f = open('fname')
header = [next(f) for _ in range(header_len)]
Since you're going to write header back to the new files, you don't need to do anything with it. To write it back to the new file:
open('new', 'w').writelines(header + list_of_lines)
if you know the number of lines in the old file, list_of_lines
would become:
list_of_lines = [next(f) for _ in range(chunk_len)]