python - 如何根据多个条件删除csv文件中的一行?
问题描述
我想读取一个 CSV 文件并根据三个条件(type、srcaddr、dstaddr )删除该 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
解决方案
您可以使用逻辑运算符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
推荐阅读
- linux - 我可以从哪里开始进入网络和黑客领域的旅程?
- sql - 大型 SQL“IN”子句和数百万行的快速结果
- websocket - 向服务器发送数据时出现 Python Flask Socketio BadNamespaceError
- mysql - MySQL查询没有给我平均的,饱和的未知列
- android - Android Kotlin 协程在使用变量打开的片段上创建 RecyclerView
- python - on_member_join 和删除不起作用。如何让它发挥作用?
- android - Mono.AndroidTools.AdbException:尝试读取流的末尾(在 Visual Studio 上)
- java - 如何创建一个元素少于给定数组的新数组?
- javascript - webpack5 output.library 无法导入
- angular - 扩充 OktaAuthService 打字稿模块时无法编译