如何将CSV写入下一列 [英] How to write CSV into the next column

查看:88
本文介绍了如何将CSV写入下一列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有可以写入CSV的输出.但是,由于我如何将XML设置为文本,因此输出会错误地自我迭代.我已经尝试了很多修复XML输出的方法,但是看不到任何解决方法.

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.

我已经做了很多尝试,包括修改XML语句以尝试以不同的方式写入CSV,但是由于行号的原因,我似乎无法使行与我需要的方式相匹配.对于具有不同深度的语句.

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.

我真的不关心它是如何完成的,只要它匹配就可以了,因为数据最终会馈送到我的SQL数据库中.

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.

下面是我的代码,

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当前输出,

below is my CSV current output,

下面是我需要的输出,

推荐答案

这已为我修复.我基本上保持原样,将其放入CSV中,然后读取CSV,将列存储为列表,删除空格并将其导出回来.

This fixed it for me. I basically left it as is, put it into a CSV, then read the CSV, stored the columns as a list, removed blank spaces and exported it back out.

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()

这篇关于如何将CSV写入下一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆