如何在python中按列过滤行

时间:2017-09-23 14:01:23

标签: python python-2.7

我需要过滤.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"在第二列AND行中包含第四列中的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

2 个答案:

答案 0 :(得分:0)

使用str.find方法,如果找到则返回索引,否则返回-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()

答案 1 :(得分:0)

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

如您所见,此实现将ips存储在列表中,以便使用python的in运算符进行比较。