简体   繁体   English

如何使用多个 for in 语句写入 csv

[英]How to write to csv with multiple for in statements

I have a Python 3.7.3 script that reads an XML, parses what I need and is supposed to export the results to CSV.我有一个 Python 3.7.3 脚本,它读取 XML、解析我需要的内容并应该将结果导出到 CSV。 I had to go deeper in the XML tree using a for in loop for one of the fields, which throws off how the other for in statements append to csv.我不得不对其中一个字段使用 for in 循环更深入地了解 XML 树,这会导致另一个 for in 语句如何附加到 csv。

When running the below, my output file does not list the different V-ID's (refer to the third for child in root... statement), however all the other fields are correct.运行以下命令时,我的输出文件没有列出不同的 V-ID(请参阅 root... 语句中的第三个子项),但是所有其他字段都是正确的。 The V-ID's display correctly when i remove the last for in statement and move the firstFile.write statement 2 tabs to the left, but then I don't have the status, so I know the problem is in the last statement.当我删除最后一个 for in 语句并将 firstFile.write 语句 2 选项卡向左移动时,V-ID 的显示正确,但是我没有状态,所以我知道问题出在最后一个语句中。 BTW, if I move the firstFile.write statement all the way to the left, it only returns one row in the csv, but there should be 5.顺便说一句,如果我将 firstFile.write 语句一直向左移动,它只会返回 csv 中的一行,但应该有 5。

Is there a way to create a list from the output and then combine them all, or perhaps move the firstFile.write statement two tabs to the left and append the last for in statement to a specific column (essentially breaking up the firstFile.write statement)?有没有办法从输出中创建一个列表,然后将它们全部组合起来,或者将 firstFile.write 语句向左移动两个选项卡并将最后一个 for in 语句附加到特定列(本质上是分解 firstFile.write 语句)? Or do you have any other suggestions?或者您有其他建议吗? CSV 示例

import os
import sys
import glob
import xml.etree.ElementTree as ET
firstFile = open("myfile.csv", "a")
firstFile.write("V-ID,")
firstFile.write("HostName,")
firstFile.write("Status,")
firstFile.write("Comments,")
firstFile.write("Finding Details,")
firstFile.write("STIG Name,")

basePath = os.path.dirname(os.path.realpath(__file__))
xmlFile = os.path.join(basePath, "C:\\Users\\myUserName\\Desktop\\Scripts\\Python\\XMLtest.xml")
tree = ET.parse(xmlFile)
root = tree.getroot()

for child in root.findall('{http://checklists.nist.gov/xccdf/1.2}title'):
    d = child.text    

for child in root:
    for children in child.findall('{http://checklists.nist.gov/xccdf/1.2}target'):
        b = children.text

for child in root.findall('{http://checklists.nist.gov/xccdf/1.2}Group'):
    x = (str(child.attrib))
    x = (x.split('_')[6])
    a = x[:-2]

for child in root:
    for children in child:
        for childrens in children.findall('{http://checklists.nist.gov/xccdf/1.2}result'):
            x = childrens.text
            if ('pass' in x):
                c = 'Completed'
            else:
                c = 'Ongoing'
            firstFile.write("\n" + a + ',' + b + ',' + c + ',' + ',' + ',' + d)
firstFile.close()

Finally, took about a week to figure this out.最后,花了大约一周的时间来解决这个问题。 I the output to CSV, then read it back into a list for each column, parsed the spaces and wrote it out again.我将输出转换为 CSV,然后将其读回到每列的列表中,解析空格并再次写出。 Below is how I did it.下面是我是如何做到的。

import os
import sys
import glob
import csv
import xml.etree.ElementTree as ET
firstFile = open("myfile.csv", "a")
path = 'C:\\Users\\JT\\Desktop\\Scripts\\Python\\xccdf\\'
for fileName in glob.glob(os.path.join(path, '*.xml')):
    with open('C:\\Users\\JT\\Desktop\\Scripts\\Python\\myfile1.csv', 'w', newline='') as csvFile1:
        csvWriter = csv.writer(csvFile1, delimiter=',')
        # do your stuff
        tree = ET.parse(fileName)
        root = tree.getroot()
        # Stig Title
        for child in root.findall('{http://checklists.nist.gov/xccdf/1.2}title'):
            d = child.text    
        # hostName
        for child in root:
            for children in child.findall('{http://checklists.nist.gov/xccdf/1.2}target'):
                b = children.text
        # V-ID    
        for child in root.findall('{http://checklists.nist.gov/xccdf/1.2}Group'):
            x = (str(child.attrib))
            x = (x.split('_')[6])
            a = x[:-2]
            firstFile.write(a + '\n')
        # Status
        for child in root:
            for children in child:
                for childrens in children.findall('{http://checklists.nist.gov/xccdf/1.2}result'):
                    x = childrens.text
                    firstFile.write(',' + b + ',' + x + ',' + ',' + ',' + d + '\n')

with open('C:\\Users\\JT\\Desktop\\Scripts\\Python\\myfile.csv', 'r') as csvFile:
    csvReader = csv.reader(csvFile, delimiter=',')
    vIDs = []
    hostNames = []
    status = []
    stigTitles = []
    for line in csvReader:
        vID = line[0]
        vIDs.append(vID)
        try:
            hostName = line[1]
            hostNames.append(hostName)
        except:
            pass
        try:
            state = line[2]
            status.append(state)
        except:
            pass
        try:
            stigTitle = line[5]
            stigTitles.append(stigTitle)
        except:
            pass

    with open('C:\\Users\\JT\\Desktop\\Scripts\\Python\\myfile1.csv', 'a', newline='') as csvFile1:
        csvWriter = csv.writer(csvFile1, delimiter=',')
        vIDMod = list(filter(None, vIDs))
        hostNameMod = list(filter(None, hostNames))
        statusMod = list(filter(None, status))
        stigTitlesMod = list(filter(None, stigTitles))
        csvWriter.writerows(zip(vIDMod, hostNameMod, statusMod, stigTitlesMod))
        firstFile.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM