如何使用一个函数跳过几个文件中的行?

时间:2016-07-12 16:01:26

标签: python csv header

我需要一些帮助。我有四个不同的文件,我想打开它,只读取文件,同时跳过每个单独文件的标题到一个函数。这是我到目前为止所得到的,但我甚至不确定如何从这里前进:

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) 

整个想法是减少编码空间,所以我只能使用那个函数来跳过每个文件中的标题,并能够打印每个文件来测试它。任何帮助都会做人!谢谢!注意:如果您想编辑问题,请随意。

1 个答案:

答案 0 :(得分:1)

你可以有这样的功能:

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

并称之为:

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

虽然真的如此,但我认为没有任何功能就可以了,只要在每个阅读器上声明next(),就会声明:

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)

或者您可以创建一个将file()csv.reader()next()功能合二为一的功能:

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

然后像这样称呼它:

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')