如何删除 CSV 文件中的列? [英] How to delete columns in a CSV file?

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

问题描述

我已经能够使用本网站上几个用户的输入使用 python 创建一个 csv,我想对您的帖子表示感谢.我现在被难住了,我会发布我的第一个问题.

I have been able to create a csv with python using the input from several users on this site and I wish to express my gratitude for your posts. I am now stumped and will post my first question.

我的 input.csv 如下所示:

My input.csv looks like this:

day,month,year,lat,long
01,04,2001,45.00,120.00
02,04,2003,44.00,118.00

我正在尝试删除年份"列及其所有条目.总共有 40 多个条目,年份范围从 1960 年到 2010 年.

I am trying to delete the "year" column and all of its entries. In total there is 40+ entries with a range of years from 1960-2010.

推荐答案

import csv
with open("source","rb") as source:
    rdr= csv.reader( source )
    with open("result","wb") as result:
        wtr= csv.writer( result )
        for r in rdr:
            wtr.writerow( (r[0], r[1], r[3], r[4]) )

顺便说一句,for 循环可以删除,但并没有真正简化.

BTW, the for loop can be removed, but not really simplified.

        in_iter= ( (r[0], r[1], r[3], r[4]) for r in rdr )
        wtr.writerows( in_iter )

此外,您可以以超文字方式满足删除列的要求.我发现这通常是一个糟糕的政策,因为它不适用于删除多个列.当您尝试删除第二个时,您会发现所有位置都发生了变化,结果行并不明显.但仅对一列而言,这是有效的.

Also, you can stick in a hyper-literal way to the requirements to delete a column. I find this to be a bad policy in general because it doesn't apply to removing more than one column. When you try to remove the second, you discover that the positions have all shifted and the resulting row isn't obvious. But for one column only, this works.

            del r[2]
            wtr.writerow( r )

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

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