Why do I have to open my csv twice?
Question: Assume I have a csv file where I first need to get the number of rows in order
to initialize an array. Then I want to fill the array with the rows from the
file (but only some columns):

    
    
    import csv
    import numpy
    
    with open('a_csv_file', 'rb') as f:
        num_row = sum(1 for row in f)
        myarray = numpy.empty(shape=(num_row, 50), dtype=numpy.int16)
        infileReader = csv.reader(f)
        for row in infileReader:
            row_number = infileReader.line_num - 1
            my_array[row_number] = [int(row[7])] + row[21:70]
    

However, the script doen't enter the row-loop. But `print infileReader` is
confirms the existence of `infileReader`.

Now I open `a_csv_file.csv` twice, but I think that's not pythonic:

    
    
    with open('a_csv_file', 'rb') as f:
        num_row = sum(1 for row in f)
    
    myarray = numpy.empty(shape=(num_row, 50), dtype=numpy.int16)
    
    with open('a_csv_file', 'rb') as f:
        infileReader = csv.reader(f)
        for row in infileReader:
            row_number = infileReader.line_num - 1
            my_array[row_number] = [int(row[7])] + row[21:70]
    

Why do I have to open the csv file twice?


Answer: When you iterate through the file (to count the length), your position in the
file is left at the end. When you try and iterate over it again, there is
nothing left so the loop is not entered. Before you create the `csv.reader`
call `f.seek(0)` to return to the start.

See the docs for the `seek` method
[here](https://docs.python.org/3.4/library/io.html#io.IOBase.seek)

