-1

I need some help. I have four different files to which I would like to open and only read the files while skipping the headers for each individual file into a function. This is what I got so far but i'm not even sure how to move forward from here:

import csv

particle_counter = file('C:/Users/Desktop/Level 2    files/HiSAM1_data_160206_134230.csv','rU')
gas_csv = file('C:/Users/Desktop/Level 2 files/gas_0.csv','rU')
gps_csv = file('C:/Users/Desktop/Level 2 files/gps_0.csv','rU')
pm2_5_csv = file('C:/Users/Desktop/Level 2 files/pm25_0.csv','rU')

reader1 = csv.reader(particle_counter)
reader2 = csv.reader(gas_csv)
reader3 = csv.reader(gps_csv)
reader4 = csv.reader(pm2_5_csv)

def skipline(n,filename):

    x =1
    while x < n in filename:
        return csv.reader.next(filename) 

The whole idea is to reduce space in my coding so I can only use that one function to skip the header in each individual file and be able to print each file to test it out. Any help will do guys! Thanks! Note: please feel free if you feel like editing the question.

user665997
  • 313
  • 1
  • 4
  • 18
  • This may be relevant to your interests: http://stackoverflow.com/questions/14257373/skip-the-headers-when-editing-a-csv-file-using-python – Caius Jul 12 '16 at 16:06
  • So what is your actual question? – Julien Jul 12 '16 at 16:31
  • how do you skiplines to several files taking into account each file has different number of headers. That's my question hahah ! sorry for the terrible wording. – user665997 Jul 12 '16 at 16:40

1 Answers1

1

You could have a function like this:

def skipline(readerlist):
    for reader in readerlist:
        next(reader)

And call it like this:

skipline([reader1, reader2, reader3, reader4])

Although really, I think it would be just fine to do without a function at all, and just call next() on each reader as it's declared:

reader1 = csv.reader(particle_counter)
next(reader1)

reader2 = csv.reader(gas_csv)
next(reader2)

reader3 = csv.reader(gps_csv)
next(reader3)

reader4 = csv.reader(pm2_5_csv)
next(reader4)

Or you could make a function that combines the file(), csv.reader() and next() functionality all into one:

def skip_header(filename):
    fp = file(filename, 'rU')
    reader = csv.reader(fp)
    next(reader)
    return reader

And then call it like this:

particle_reader = skip_header('C:/Users/Desktop/Level 2 files/HiSAM1_data_160206_134230.csv')
gas_reader = skip_header('C:/Users/Desktop/Level 2 files/gas_0.csv')
gps_reader = skip_header('C:/Users/Desktop/Level 2 files/gps_0.csv')
pm2_5_reader = skip_header('C:/Users/Desktop/Level 2 files/pm25_0.csv')
John Gordon
  • 29,573
  • 7
  • 33
  • 58