Sometimes, we want to skip the headers when editing a csv file using Python.
In this article, we’ll look at how to skip the headers when editing a csv file using Python.
How to skip the headers when editing a csv file using Python?
To skip the headers when editing a csv file using Python, we can call next
to skip the first row.
For instance, we write
with open("foo.csv", "rb") as infile, open("bar.csv", "wb") as outfile:
reader = csv.reader(infile)
next(reader, None)
writer = csv.writer(outfile)
for row in reader:
writer.writerow(row)
to open the foo.csv and bar.csv files with open
.
And then we call csv.reader
to read infile
into an iterator.
Then we call next
with reader
to skip the header row.
Then we call csv.writer
with outfile
to create the writer
object.
Then we loop through the rows returned by reader
and call writerow
to write the row
.
Conclusion
To skip the headers when editing a csv file using Python, we can call next
to skip the first row.