python的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.

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

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

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值