使用Python删除或删除CSV文件中的最后一列

时间:2022-03-17 11:10:21

I have a CSV file with 5 columns. Using Python, how can I delete the last column (header5 in the example)? Is there an easy way I'm missing, or do I have to loop through all rows in the CSV and remove each value from the last column (which could still leave me with the undesired preceding comma)?

我有一个包含5列的CSV文件。使用Python,我如何删除最后一列(示例中的header5)?有一种简单的方法我缺少,或者我是否必须遍历CSV中的所有行并从最后一列中删除每个值(这可能仍然留下我不想要的前面的逗号)?

I'm not seeing anything related to this in the CSV module or elsewhere on the interwebs, so any help is much appreciated.

我没有在CSV模块或互联网上的其他地方看到与此相关的任何内容,因此非常感谢任何帮助。

header1,header2,header3,header4,header5
value1,value2,value3,value4,value5
value1,value2,value3,value4,value5

2 个解决方案

#1


13  

Use the csv module. When writing out a row, use row[:-1] to chop off the last item:

使用csv模块。写出一行时,使用行[: - 1]来删除最后一项:

import csv

with open(filename,"r") as fin:
    with open(outname,"w") as fout:
        writer=csv.writer(fout)
        for row in csv.reader(fin):
            writer.writerow(row[:-1])

#2


1  

Even if you don't use CSV module, the logical and sane way is to read the file row by row, split them on comma, and print out item 1 through 4 with a join. eg

即使您不使用CSV模块,逻辑和理智的方法是逐行读取文件,将它们拆分为逗号,并使用连接打印出项目1到4。例如

for line in open("file"):
    print ','.join( line.split(",")[:-1] )

Or just by simple string indexing

或者只是通过简单的字符串索引

for line in open("file"):
    print line[ : line.rindex(",") ]

#1


13  

Use the csv module. When writing out a row, use row[:-1] to chop off the last item:

使用csv模块。写出一行时,使用行[: - 1]来删除最后一项:

import csv

with open(filename,"r") as fin:
    with open(outname,"w") as fout:
        writer=csv.writer(fout)
        for row in csv.reader(fin):
            writer.writerow(row[:-1])

#2


1  

Even if you don't use CSV module, the logical and sane way is to read the file row by row, split them on comma, and print out item 1 through 4 with a join. eg

即使您不使用CSV模块,逻辑和理智的方法是逐行读取文件,将它们拆分为逗号,并使用连接打印出项目1到4。例如

for line in open("file"):
    print ','.join( line.split(",")[:-1] )

Or just by simple string indexing

或者只是通过简单的字符串索引

for line in open("file"):
    print line[ : line.rindex(",") ]