Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip first line(field) in loop using CSV file? [duplicate]

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.

for row in kidfile:
    if row.firstline = false:  # <====== Something is missing here.
        continue
    if ......
like image 320
Raitis Kupce Avatar asked Feb 03 '13 15:02

Raitis Kupce


People also ask

How do I skip the first line of a CSV file?

Line 1: We import the Pandas library as a pd. Line 2: We read the csv file using the pandas read_csv module, and in that, we mentioned the skiprows=[0], which means skip the first line while reading the csv file data. Line 4: Now, we print the final dataframe result shown in the above output without the header row.

How do I skip the first line of a CSV file using Pandas?

While calling pandas. read_csv() if we pass skiprows argument with int value, then it will skip those rows from top while reading csv file and initializing a dataframe. For example if we want to skip 2 lines from top while reading users.

Is it necessary to have a line as first line in CSV file?

The first row is only mandatory when the import template has the setting use "Use column headers as configuration" enabled. However having the first row in the CSV file helps knowing what data is in the file.

Which function is used to skip a row in CSV file?

The command used to skip a row in a CSV file is skip().


3 Answers

There are many ways to skip the first line. In addition to those said by Bakuriu, I would add:

with open(filename, 'r') as f:     next(f)     for line in f: 

and:

with open(filename,'r') as f:     lines = f.readlines()[1:] 
like image 87
Andrea Avatar answered Sep 19 '22 05:09

Andrea


The best way of doing this is skipping the header after passing the file object to the csv module:

with open('myfile.csv', 'r', newline='') as in_file:     reader = csv.reader(in_file)     # skip header     next(reader)     for row in reader:         # handle parsed row 

This handles multiline CSV headers correctly.


Older answer:

Probably you want something like:

firstline = True for row in kidfile:     if firstline:    #skip first line         firstline = False         continue     # parse the line 

An other way to achive the same result is calling readline before the loop:

kidfile.readline()   # skip the first line for row in kidfile:     #parse the line 
like image 29
Bakuriu Avatar answered Sep 23 '22 05:09

Bakuriu


csvreader.next() Return the next row of the reader’s iterable object as a list, parsed according to the current dialect.

like image 39
user2037553 Avatar answered Sep 22 '22 05:09

user2037553