Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

python - How to write CSV into the next column

I have output that I can write into a CSV. However, because of how i setup my XML to text, the output iterates itself incorrectly. I've tried a lot to fix my XML output, but I don't see any way to fix it.

I've tried a lot, including modifying my XML statements to trying to write to CSV in different ways, but I can't seem to get the rows to match up the way I need them to be, because of the the for in statements that have different depths.

I don't really care how it's done, so long as it matches up, because the data is ultimately fed into my SQL database.

Below is my code,

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("
" + 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('	' + '
' + ',' + b + ',' + c + ',' + ',' + ',' + d)
firstFile.close()

below is my CSV current output, enter image description here

below is the output I need,

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

try to change this
x = (x.split('_')[0])


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...