0

Trying to skip i rows of a data file (then process j rows). Plenty of answers on length of csv file. No success with count or .line_num.

How is current line number accessed in csv.reader?

import csv
def csv_reader(df):
    i = 90    
    with open(df, 'r') as csvfile:
            for line in range(0, i):
                next(csvfile)
            for line in csv.reader(csvfile, delimiter=' ', skipinitialspace = True):
                print(csv.reader.line_num)  # Invalid line

Sample data:

Last Quarter
Visit Astronomy
Daily Weather History & Observations
2018    Temp. (°C)  Dew Point (°C)  Humidity (%)    Sea Level Press. (hPa)  Visibility (km) Wind (km/h) Precip. (mm)    Events
Mar high    avg low high    avg low high    avg low high    avg low high    avg low high    avg high    sum  
1   27  19  12  13  9   4   82  49  21  1016    1012    1007    10  10  10  24  11  -   0.00     
2   25  20  14  14  12  9   82  61  32  1017    1014    1010    10  10  10  21  10  -   0.00     
3   31  22  14  15  13  7   94  59  13  1014    1011    1007    10  10  10  27  8   -   0.00     
4   30  21  13  15  13  6   82  59  13  1016    1012    1009    10  10  10  34  11  -   0.00     
5   24  19  15  16  13  11  82  71  46  1022    1016    1013    10  10  10  35  13  -   0.00    Rain
6   20  14  9   12  9   6   82  60  31  1028    1024    1021    10  10  10  32  19  47  0.00     
7   23  16  9   13  10  7   100 71  29  1029    1027    1024    10  10  5   29  11  37  0.00    Rain
Other random data follows
flywire
  • 1,155
  • 1
  • 14
  • 38

1 Answers1

1

You can access line number using enumerate.

for index, line in enumerate(csv.reader(csvfile, delimiter=' ', skipinitialspace = True)):
    print('Index %s' % str(index + 1))  # enumerate starts with 0
Nishant Nawarkhede
  • 8,234
  • 12
  • 59
  • 81
  • Unfortunate sting in the tail - in consumes a line with my use case - https://stackoverflow.com/a/49991586/4539999 – flywire Apr 24 '18 at 10:17