Pythonic method to sum all the odd-numbered lines in a file
Question: I'm learning Python for a programming placement test I have to take for grad
school, and this is literally the first little script I threw together to get
a feel for it. My background is mainly C# and PHP, but I can't use either
language on the test.

My test script reads in the below text file (test_file1.txt). The even lines
contain a sample size, and the odd lines contain "results" for each test in
the sample. EOF is marked with a 0. I wanted to read in the file, output the
sample size, and sum the results of each test. How would you perform this task
with Python? I feel like I was trying to force python to be like PHP or C#,
and from my research I guess there are very "Python" ways of doing thigs.

test_file1.txt:

    
    
    3
    13 15 18
    5 
    19 52 87 55 1
    4
    11 8 63 4
    2
    99 3
    0
    

My simple script:

    
    
    file = open("test_file1.txt", "r")
    
    i=0
    for line in file:
        if i % 2 == 0:
            #num is even
            if line == '0':
                #EOF
                print 'End of experiment'   
        else:
            #num is odd
            numList = line.split( )
            numList = [int(x) for x in numList]
            print 'Sample size: ' + str(len(numList)) + ' Results: ' + str(sum(numList))
        i += 1
    
    file.close()
    

My results:

    
    
    Sample size: 3 Results: 46
    Sample size: 5 Results: 214
    Sample size: 4 Results: 86
    Sample size: 2 Results: 102
    End of experiment
    

Thanks!


Answer: Use the file as an iterator, then use
[`iterators.islice()`](http://docs.python.org/2/library/itertools.html#itertools.islice)
to get every second line:

    
    
    from itertools import islice
    
    with open("test_file1.txt", "r") as f:
       for line in islice(f, 1, None, 2):
           nums = [int(n) for n in line.split()]
           print 'Sample size: {}  Results: {}'.format(len(nums), sum(nums))
    

`islice(f, 1, None, 2)` skips the first line (`start=1`), then iterates over
all lines (`stop=None`) returning every second line (`step=2`).

This'll work with whatever filesize you throw at it; it won't need any more
memory than required by the internal iterator buffer.

Output for your test file:

    
    
    Sample size: 3  Results: 46
    Sample size: 5  Results: 214
    Sample size: 4  Results: 86
    Sample size: 2  Results: 102
    

