Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing the first line of CSV file [duplicate]

Tags:

python

csv

line

How would I remove the first line of a CSV file in python, the first few lines of my CSV file are:

Domain Name, ItemID, Auction Type, Time Left, Price, Bids, Domain Age, Traffic,ValuationPrice
TICKETFINE.COM,134774365,Bid,05/09/2014 08:00 AM (PDT),$100,0,0,0,$0
CREATINGMY.COM,134774390,Bid,05/09/2014 08:00 AM (PDT),$500,0,0,0,$0
WPTHEMEHELP.COM,134774444,Bid,05/09/2014 08:00 AM (PDT),$45,1,0,0,$0
APK-ZIPPY.COM,134774445,Bid,05/09/2014 08:00 AM (PDT),$10,0,0,0,$0
FAMILYBUZZMARKETING.COM,134689583,Bid,05/09/2014 08:00 AM (PDT),$90,0,0,0,$0
AMISRAGAS.COM,134689584,Bid,05/09/2014 08:00 AM (PDT),$35,0,0,0,$0
like image 242
Coder77 Avatar asked May 12 '14 17:05

Coder77


3 Answers

with open("test.csv",'r') as f:
    with open("updated_test.csv",'w') as f1:
        next(f) # skip header line
        for line in f:
            f1.write(line)
like image 98
Padraic Cunningham Avatar answered Nov 15 '22 00:11

Padraic Cunningham


For anyone else caught up this error:

AttributeError: '_io.TextIOWrapper' object has no attribute 'next' python

In Python3 a text file object doesn't have a next() function. So you can't call f.next().

Instead you should use f.readline() as specified in this answer.

Or you can use the built-in next(f) which @vrjr mentioned in the comment, and is shown in this answer.

like image 44
Yep_It's_Me Avatar answered Nov 14 '22 23:11

Yep_It's_Me


This is what I do when I want to skip reading the first line of a CSV.

All that has to be done is call the next() function of the CSV object, in this case - read, and then the pointer to the reader will be on the next line.

import csv

try:
    read = csv.reader(f)
    read.next()     # Skip the first 'title' row.
    for r in read:
        # Do something
finally:
    # Close files and exit cleanly
    f.close()

Hope this is pretty clean an simple for your purposes!

like image 1
Signus Avatar answered Nov 14 '22 22:11

Signus