删除多个csv文件python中的前4行

时间:2017-04-17 12:33:26

标签: python csv

我知道如何删除CSV文件中的行,但是要查看删除多个CSV文件中的多行。

这是我的代码:

import csv
import os
import glob

myfiles = glob.glob('*.csv',recursive=False)

with open(myfiles, 'r') as fin:
    data = fin.read().splitlines(True)
with open(myfiles, 'w') as fout:
    fout.writelines(data[5:])

我想实现以下目标: 1)遍历当前目录。 2)删除CSV文件中的前4行并保存。

2 个答案:

答案 0 :(得分:2)

This回答看起来很有帮助。以下是处理多个文件的轻微调整:

import glob

myfiles = glob.glob('*.csv')
for file in myfiles:
    lines = open(file).readlines()
    open(file, 'w').writelines(lines[3:])

答案 1 :(得分:0)

如果你想使用python,你可以这样做。

import csv
import os

def read_csv(inputfile, outputfile):
     try:

        with open(inputfile, 'r') as csvfile:

            file = csv.reader(csvfile, delimiter='|', lineterminator = '\n')
            for i, line in enumerate(file):
            if i > 3:
                write_csv(line,outputfile)

     except IOError:
            print "IOError in ", inputfile


def write_csv(w_list, outputfile):
    with open(outputfile, 'a') as f:
        writer = csv.writer(f, delimiter = '|', lineterminator = '\n')
        writer.writerows(w_list)


def main():

    indir = 'path to dir with csv'


    for root, dirs, filenames in os.walk(indir):
        for f in filenames:
            filename = os.path.join(root , f)
            if '.csv' in filename:
                read_csv(filename, outputfile='output' +filename)


if __name__=="__main__":
    main()

或者您可以使用:

tail -n +4 original.csv > original-4-top-lines.csv