How can one remove the header line in a file using Python

How can one remove the header line in a file using Python?

Thanks.
B BelousAsked:
Who is Participating?
 
peprCommented:
In my opinion, the best way to read the file is to use the standard csv module. After opening the CSV file and wrapping it with csv.reader() the header can be skipped using next(reader) like this:
import csv

fname = 'myfile.csv'
with open(fname, newline='') as f:
    reader = csv.reader(f)
    next(reader)          # <==== this will skip one row (the header)
    for row in reader:
        process_somehow_the(row)

Open in new window

0
 
peprCommented:
What header line from what file? It may depend what kind of file it is, and how it is going to be processed.

Thinking about the header line as the first line of the text file, then you have to open it in text mode, skip one line, and write the content into another file -- possibly renaming the source and the destination files so that the new file will use the original name.
0
 
B BelousAuthor Commented:
This is a CSV file. I wanted to remove the first line.

Thanks.
0
 
B BelousAuthor Commented:
Great. Thanks!
0
 
NorieVBA ExpertCommented:
I see you have a solution but I'll post this anyway, it reads a CSV file named 'testfile.csv' and writes the data, without the header, to a new file, 'newtestfile.csv'.
import csv

fname = 'testfile.csv'
with open(fname, 'rb') as f:
    rd = csv.reader(f)
    next(rd)
    data = list(rd)
    newf = open('newtestfile.csv', 'wb')
    wr = csv.writer(newf)    
    for row in data:
        wr.writerow(row)
    newf.close()

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.