Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to ignore for loop control variable

Tags:

python

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 i. 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.

like image 641
GreenMatt Avatar asked Dec 11 '09 04:12

GreenMatt


People also ask

How do you force stop a for loop in Python?

In Python, the break statement provides you with the opportunity to exit out of a loop when an external condition is triggered. You'll put the break statement within the block of code under your loop statement, usually after a conditional if statement.

How do you break a for loop in Python?

Python provides two keywords that terminate a loop iteration prematurely: The Python break statement immediately terminates a loop entirely. Program execution proceeds to the first statement following the loop body. The Python continue statement immediately terminates the current loop iteration.

How do you abort a for loop?

Tips. The break statement exits a for or while loop completely. To skip the rest of the instructions in the loop and begin the next iteration, use a continue statement. break is not defined outside a for or while loop.


2 Answers

I'm not sure what the Pylint rules are, but you could use the '_' throwaway variable name.

header = ''
header_len = 4
for _ in range(1, header_len):
    header += file_handle.readline()
like image 67
David Claridge Avatar answered Sep 28 '22 05:09

David Claridge


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)]
like image 44
SilentGhost Avatar answered Sep 28 '22 05:09

SilentGhost