使用CSV文件中的Python删除行 [英] Deleting rows with Python in a CSV file

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

问题描述

我想做的就是删除第三行中值为'0'的行.数据示例如下:

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

任何帮助都会很棒

推荐答案

您非常亲密;当前,您将row[2]与整数0进行比较,并与字符串"0"进行比较.当您从文件中读取数据时,它是一个字符串而不是整数,因此这就是您的整数检查当前失败的原因:

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":

此外,您可以使用with关键字使当前代码更具pythonic性,从而减少代码中的行,并可以省略.close语句:

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)

请注意,input是Python内置的,所以我改用了另一个变量名.

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

编辑 :csv文件行中的值用逗号分隔;在普通的csv中,它们将简单地用逗号分隔,并且可以对"0"进行检查,因此您可以使用strip(row[2]) != 0或对" 0"进行检查.

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".

更好的解决方案是更正csv格式,但是如果您要保留当前的csv格式,则以下将适用于您给定的csv文件格式:

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

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

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