使用Python将数据追加到CSV的前一行

2024-06-28 11:23:40 发布

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

我正在编写一个Python脚本,它接受以CSV形式导出的Nessus数据并删除重复数据,但是由于导出的方式,不同端口和协议的结果都有自己唯一的行,即使行中的所有其他数据都是相同的。我需要删除这些重复项,但我希望保留端口和协议列数据并将其附加到上一行。在

下面是我用来测试和构建脚本的一个非常小的CSV:

Screenshot of CSV File

正如您所看到的,除了端口字段之外,所有字段都是完全相同的,有时协议字段也会不同,所以我需要读取CSV文件的两行,然后像这样附加端口:80、443和协议一样:tcp,tcp

然后只保存一行来删除重复的数据,我试着通过检查是否已经有一个插件ID的实例来执行此操作,但是我的输出只是打印第二行的端口和协议。在

protocollist = []
portlist = []
pluginid_list = []
multiple = False 

with open(csv_file_input, 'rb') as csvfile:
    nessusreader = csv.DictReader(csvfile)
    for row in nessusreader:
        pluginid = row['Plugin ID']
        if pluginid != '':
            pluginid_list.append(row['Plugin ID'])
            print(pluginid_list)
        count = pluginid_list.count(pluginid)
        cve = row['CVE']
        if count > 0:
            protocollist.append(row['Protocol'])
            print(protocollist)
            portlist.append(row['Port'])
            print(portlist)
            print('Counted more than 1')
            multiple = True
        if multiple == True:
            stringlist = ', '.join(protocollist)
            newstring1 = stringlist
            protocol = newstring1
            stringlist2 = ', '.join(portlist)
            newstring2 = stringlist2
            port = newstring2
        else:
            protocol = row['Protocol']
            port = row['Port']
        cvss = row['CVSS']
        risk = row['Risk']
        host = row['Host']
        name = row['Name']
        synopsis = row['Synopsis']
        description = row['Description']
        solution = row['Solution']
        seealso = row['See Also']
        pluginoutput = row['Plugin Output']

with open(csv_file_output, 'w') as csvfile:
    fieldnames = ['Plugin ID', 'CVE', 'CVSS', 'Risk', 'Host', 'Protocol', 'Port', 'Name', 'Synopsis', 'Description', 'Solution', 'See Also', 'Plugin Output']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({'Plugin ID': pluginid, 'CVE': cve, 'CVSS': cvss, 'Risk': risk, 'Host': host, 'Protocol': protocol, 'Port': port, 'Name': name, 'Synopsis': synopsis, 'Description': description, 'Solution': solution, 'See Also': seealso, 'Plugin Output': pluginoutput})

代码中可能有一些错误,因为我一直在尝试不同的东西,但我只想展示我一直在做的代码,以便为这个问题提供更多的上下文。如果数据只显示在CSV中,因为只有两个项目,那么这段代码可以工作,但是我引入了第三组具有不同插件ID的数据,然后它也将其添加到列表中,可能是因为if语句被设置为>;0。在


Tags: csv数据csvfile端口id协议ifplugin