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

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

B BelousAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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.
B BelousAuthor Commented:
This is a CSV file. I wanted to remove the first line.

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:

Open in new window


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
B BelousAuthor Commented:
Great. Thanks!
NorieAnalyst Assistant Commented:
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)
    data = list(rd)
    newf = open('newtestfile.csv', 'wb')
    wr = csv.writer(newf)    
    for row in data:

Open in new window

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.