使用Python删除或删除CSV文件中的最后一列 [英] Delete or remove last column in CSV file using Python

查看:859
本文介绍了使用Python删除或删除CSV文件中的最后一列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我没有在CSV模块或网络上的其他地方看到任何与此相关的内容,所以任何帮助都非常感激。

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

使用 csv模块。当写出一行时,使用 row [: - 1] 来截断最后一个项目:

  import csv 

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


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)?

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

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

解决方案

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

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])

这篇关于使用Python删除或删除CSV文件中的最后一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆