且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 Python 删除 CSV 文件中的行

更新时间:2023-10-04 20:28:04

你们很亲近;当前您将 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 文件格式:

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