首页 > 解决方案 > 如何根据多个条件删除csv文件中的一行?

问题描述

我想读取一个 CSV 文件并根据三个条件(typesrcaddrdstaddr )删除该 CSV 文件中的一行。

例如,如果我输入第一个条件是'icmp'第二个条件是'10.0.0.1'第三个条件是'10.0.0.2',它只会删除该特定行。

我曾尝试使用此代码,但它只允许我根据一个条件删除,我如何修改它以允许它根据多个条件删除?

#code that I used to delete a row in CSV file based on only one condition.

import csv
import sys


with open('firewall-policies-test.csv', "rb") as f:
    data = list(csv.reader(f))

with open('firewall-policies-test.csv', "wb") as f:
    writer = csv.writer(f)
    for row in data:
        if row[0] != 'icmp':
              writer.writerow(row)   






 #code for CSV File
 type,srcaddr,dstadrr
 icmp,10.0.0.1,10.0.0.2
 tcp,10.0.0.1,10.0.0.2

当我尝试使用 and & or 运算符时,它总是给我一个错误,说列表索引超出范围。

Traceback (most recent call last):
  File "deletecsv.py", line 11, in <module>
    if row[0] != "icmp" and row[1] != '10.0.0.1' and row[2] != '10.0.0.2':
IndexError: list index out of range

标签: pythoncsv

解决方案


您可以使用逻辑运算符and或“链接”多个条件or

if row[0] != 'icmp' and row[1] != 'foo' and row[2] != 'bar':
  # do thing

以下是更多示例和解释:

https://thomas-cokelaer.info/tutorials/python/boolean.html#boolean-examples


推荐阅读