GreenMatt GreenMatt - 1 year ago 77
Python Question

Pythonic way to ignore for loop control variable

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 something similar to the following:

header = ''
header_len = 4
for i in range(1, header_len):
header += file_handle.readline()

Pylint complains that I'm not using the variable
. What would be a more pythonic way to do this?

Edit: The purpose of the program is to intelligently split the original file into smaller files, each of which contains the original header and a subset of the data. So, I need to read and preserve just the header before reading the rest of the file.

Answer Source
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)]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download