我有一个python3.7.3脚本,它读取XML,解析我需要的内容,并将结果导出到CSV。我不得不在XML树中更深入地使用一个for-in循环来表示其中一个字段,这样就忽略了另一个for-in语句是如何附加到csv的。你知道吗
当运行下面的时,我的输出文件没有列出不同的V-ID(请参阅根目录中的第三个for child。。。语句),但是所有其他字段都是正确的。当我删除最后一个for in语句并移动firstFile.write文件语句左边有两个选项卡,但是我没有状态,所以我知道问题出在最后一个语句中。顺便说一句,如果我移动firstFile.write文件语句,它只返回csv中的一行,但应该有5行。你知道吗
有没有办法从输出中创建一个列表,然后将它们全部合并,或者移动firstFile.write文件语句左边有两个制表符,并将最后一个for-in语句附加到一个特定的列中(基本上分解了firstFile.write文件声明)?或者你还有其他建议吗?
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()
最后,花了大约一周的时间才弄明白。我将输出转换为CSV,然后将其读回每列的列表,解析空格并再次写出。下面是我是怎么做到的。你知道吗
相关问题 更多 >
编程相关推荐