Removing the first line of CSV file [duplicate]

≯℡__Kan透↙ 提交于 2020-02-19 06:52:52

问题


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

回答1:


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)



回答2:


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!




回答3:


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.




回答4:


Are you opening it and re-saving it with the same name?

Otherwise, you could read it in without reading in the first line and writing to a new file without that line.




回答5:


  • Read the file line-by-line
  • Write each line to a new file, omitting the first
  • replace the first file with the second


来源:https://stackoverflow.com/questions/23615496/removing-the-first-line-of-csv-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!