|
Jul 29, 2017 Possible Duplicate: When processing CSV data, how do I ignore the first line of data? I am using python to open CSV file. I am using formula loop but I need to skip the first row because it has header. So far I remember was something like this but it is missing something: I wonder if someone knows the code for what I am trying to do. The data can be read using: from pandas import DataFrame, readcsv import matplotlib.pyplot as plt import pandas as pd file = r'highscore.csv' df = pd.readcsv(file) print(df) The first lines import the Pandas module. The readcsv method loads the data in a a Pandas dataframe that we named df.
I am using below referred code to edit a csv using Python. Functions called in the code form upper part of the code.
Problem: I want the below referred code to start editing the csv from 2nd row, I want it to exclude 1st row which contains headers. Right now it is applying the functions on 1st row only and my header row is getting changed.
I tried to solve this problem by initializing row
variable to 1
but it didn't work.
Please help me in solving this issue.
3 Answers
Your reader
variable is an iterable, by looping over it you retrieve the rows.
To make it skip one item before your loop, simply call next(reader, None)
and ignore the return value.
You can also simplify your code a little; use the opened files as context managers to have them closed automatically:
If you wanted to write the header to the output file unprocessed, that's easy too, pass the output of next()
to writer.writerow()
:
Another way of solving this is to use the DictReader class, which 'skips' the header row and uses it to allowed named indexing.
Given 'foo.csv' as follows:
Use DictReader like this:
Doing row=1
won't change anything, because you'll just overwrite that with the results of the loop.
You want to do next(reader)
to skip one row.
protected by Vamsi PrabhalaNov 5 '18 at 1:57
Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?