python删除csv行,使用CSV文件中的Python删除行

All I would like to do is delete a row if it has a value of '0' in the third column. An example of the data would be something like:

6.5, 5.4, 0, 320

6.5, 5.4, 1, 320

So the first row would need to be deleted whereas the second would stay.

What I have so far is as follows:

import csv

input = open('first.csv', 'rb')

output = open('first_edit.csv', 'wb')

writer = csv.writer(output)

for row in csv.reader(input):

if row[2]!=0:

writer.writerow(row)

input.close()

output.close()

Any help would be great

解决方案

You are very close; currently you compare the row[2] with integer 0, make the comparison with the string "0". When you read the data from a file, it is a string and not an integer, so that is why your integer check fails currently:

row[2]!="0":

Also, you can use the with keyword to make the current code slightly more pythonic so that the lines in your code are reduced and you can omit the .close statements:

import csv

with open('first.csv', 'rb') as inp, open('first_edit.csv', 'wb') as out:

writer = csv.writer(out)

for row in csv.reader(inp):

if row[2] != "0":

writer.writerow(row)

Note that input is a Python builtin, so I've used another variable name instead.

Edit: The values in your csv file's rows are comma and space separated; In a normal csv, they would be simply comma separated and a check against "0" would work, so you can either use strip(row[2]) != 0, or check against " 0".

The better solution would be to correct the csv format, but in case you want to persist with the current one, the following will work with your given csv file format:

$ cat test.py

import csv

with open('first.csv', 'rb') as inp, open('first_edit.csv', 'wb') as out:

writer = csv.writer(out)

for row in csv.reader(inp):

if row[2] != " 0":

writer.writerow(row)

$ cat first.csv

6.5, 5.4, 0, 320

6.5, 5.4, 1, 320

$ python test.py

$ cat first_edit.csv

6.5, 5.4, 1, 320

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值