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

查看:783
本文介绍了如何删除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

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

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天全站免登陆