首页 > 解决方案 > 如何将 CSV 写入下一列

问题描述

我有可以写入 CSV 的输出。但是,由于我将 XML 设置为文本的方式,输出会错误地自行迭代。我已经尝试了很多来修复我的 XML 输出,但我没有看到任何修复它的方法。

我已经尝试了很多,包括修改我的 XML 语句以尝试以不同的方式写入 CSV,但由于 for in 语句,我似乎无法让行与我需要的方式匹配有不同的深度。

我真的不在乎它是如何完成的,只要它匹配,因为数据最终会输入到我的 SQL 数据库中。

下面是我的代码,

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]
    firstFile.write("\n" + a + ',')
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('\t' + '\n' + ',' + b + ',' + c + ',' + ',' + ',' + d)
firstFile.close()

下面是我的 CSV 当前输出, 在此处输入图像描述

下面是我需要的输出,

在此处输入图像描述

标签: pythoncsvelementtree

解决方案


尝试改变这个
x = (x.split('_')[0])


推荐阅读