如何在python中按列筛选行

2024-05-29 01:35:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要过滤.csv文件的一些行:

2017/06/07 10:42:35,THREAT,url,192.168.1.100,52.25.xxx.xxx,Rule-VWIRE-03,13423523,,web-browsing,80,tcp,block-url
2017/06/07 10:43:35,THREAT,url,192.168.1.101,52.25.xxx.xxx,Rule-VWIRE-03,13423047,,web-browsing,80,tcp,allow
2017/06/07 10:43:36,THREAT,end,192.168.1.102,52.25.xxx.xxx,Rule-VWIRE-03,13423047,,web-browsing,80,tcp,block-url
2017/06/07 10:44:09,TRAFFIC,end,192.168.1.101,52.25.xxx.xxx,Rule-VWIRE-03,13423111,,web-browsing,80,tcp,allow
2017/06/07 10:44:09,TRAFFIC,end,192.168.1.103,52.25.xxx.xxx,Rule-VWIRE-03,13423111,,web-browsing,80,tcp,block-url

我想过滤第二列中包含字符串“THREAT”的行,以及第四列中包含ips 192.168.1.100和192.168.1.101的行。你知道吗

这是我迄今为止的实现:

import csv

file= open(file.log, 'r')
f= open(column, 'w')
lines = file.readlines() 
for line in lines:
        input = raw_input()
        col = line.split(',') 
        if line.find(col[1])=="THREAT":
                f.write (line)
        if line.find(col[3]==192.168.1.100 && 192.168.101:
                f.write (line)
        else:
                pass

f.close()
file.close()

代码有什么问题?这是我期望得到的输出:

2017/06/07 10:42:35,THREAT,url,192.168.1.100,52.25.xxx.xxx,Rule-VWIRE-03,13423523,,web-browsing,80,tcp,block-url
2017/06/07 10:43:35,THREAT,url,192.168.1.101,52.25.xxx.xxx,Rule-VWIRE-03,13423047,,web-browsing,80,tcp,allow

Tags: csvweburllinecolblockruletcp
2条回答

您使用str.find方法,如果找到该方法,则返回index,否则返回-1。在您的例子中—例如,如果THREAT在第行—它将返回一些非零的数字,但是您将该数字与字符串进行比较,这显然是返回False。 此外,还可以合并这些if语句。你知道吗

因此,考虑到上述情况,您的if语句应该是:

if col[1] == "THREAT" or col[3] in ["192.168.1.100", "192.168.1.101"]:
    f.write(line)

另外-我不明白,为什么每次迭代都使用raw_input而不再使用那个值?你知道吗

我建议你使用这个小优化代码:

import csv  # not used in provide snippet, could be deleted

file_log = open("file.log", 'r')  # better to use absoulete path 
filtered_log = open("column", 'w')  # same as previous
for line in file:  # no need to read entire file, just iterate over it line by line directly
    col = line.split(',')
    if col and (col[1] == "THREAT" or col[3] in ["192.168.1.100", "192.168.1. 101"]):
        filtered_log.write(line)

file_log.close()
filtered_log.close()

Python的csv模块提供了一个reader对象,可用于迭代.csv文件行。你知道吗

在每一行中,您可以根据列的索引提取列,并在打印行之前应用一些比较逻辑。你知道吗

此实现将根据需要筛选文件:

import csv

ip_list = ['192.168.1.100', '192.168.1.101']
with open('file.csv', 'r') as csvfile:
    reader = csv.reader(csvfile)
    for line in reader:
        if (line[1]=="THREAT") and (line[3] in ip_list):
            print(','.join(line))

如您所见,这个实现将ip存储在一个列表中,以便使用python的in操作符进行比较。你知道吗

相关问题 更多 >

    热门问题