Python 删除 CSV 文件的第一行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23615496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:14:10  来源:igfitidea点击:

Removing the first line of CSV file

pythoncsvline

提问by Coder77

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

我将如何在 python 中删除 CSV 文件的第一行,我的 CSV 文件的前几行是:

Domain Name, ItemID, Auction Type, Time Left, Price, Bids, Domain Age, Traffic,ValuationPrice
TICKETFINE.COM,134774365,Bid,05/09/2014 08:00 AM (PDT),0,0,0,0,
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)
CREATINGMY.COM,134774390,Bid,05/09/2014 08:00 AM (PDT),0,0,0,0,
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()
WPTHEMEHELP.COM,134774444,Bid,05/09/2014 08:00 AM (PDT),,1,0,0,
AttributeError: '_io.TextIOWrapper' object has no attribute 'next' python
APK-ZIPPY.COM,134774445,Bid,05/09/2014 08:00 AM (PDT),,0,0,0,##代码## FAMILYBUZZMARKETING.COM,134689583,Bid,05/09/2014 08:00 AM (PDT),,0,0,0,##代码## AMISRAGAS.COM,134689584,Bid,05/09/2014 08:00 AM (PDT),,0,0,0,##代码##

采纳答案by Padraic Cunningham

##代码##

回答by mauve

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.

否则,您可以在不读取第一行并写入没有该行的新文件的情况下读取它。

回答by Signus

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

当我想跳过阅读 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.

所要做的就是调用next()CSV 对象的函数,在这种情况下 - read,然后指向阅读器的指针将位于下一行。

##代码##

Hope this is pretty clean an simple for your purposes!

希望这对于您的目的来说非常干净和简单!

回答by Yep_It's_Me

For anyone else caught up this error:

对于遇到此错误的其他人:

##代码##

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

在 Python3 中,文本文件对象没有next()函数。所以你不能打电话f.next()

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

相反,您应该f.readline()按照此答案中的说明使用

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

或者您可以使用next(f)评论中提到的@vrjr的内置函数,并显示在此答案中