Skip to content Skip to sidebar Skip to footer

Remove First 4 Lines In Multiple Csv Files Python

I know how to remove lines in a CSV file, however looking at removing multiple lines in multiple CSV files. that's my code: import csv import os import glob myfiles = glob.glob('*

Solution 1:

This answer looks helpful. Here is a slight tweak of it to handle multiple files:

import glob

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

Solution 2:

If you want to use python you can do this.

import csv
import os

defread_csv(inputfile, outputfile):
     try:

        withopen(inputfile, 'r') as csvfile:

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

     except IOError:
            print"IOError in ", inputfile


defwrite_csv(w_list, outputfile):
    withopen(outputfile, 'a') as f:
        writer = csv.writer(f, delimiter = '|', lineterminator = '\n')
        writer.writerows(w_list)


defmain():

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

Or you can use:

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

Post a Comment for "Remove First 4 Lines In Multiple Csv Files Python"