简体   繁体   English

如何将 CSV 写入下一列

[英]How to write CSV into the next column

I have output that I can write into a CSV.我有可以写入 CSV 的输出。 However, because of how i setup my XML to text, the output iterates itself incorrectly.但是,由于我将 XML 设置为文本的方式,输出会错误地迭代自身。 I've tried a lot to fix my XML output, but I don't see any way to fix it.我已经尝试了很多来修复我的 XML 输出,但我没有看到任何修复它的方法。

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

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.我并不在乎它是如何完成的,只要它匹配即可,因为数据最终会输入到我的 SQL 数据库中。

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

below is my CSV current output,下面是我的 CSV 当前输出, 在此处输入图片说明

below is the output I need,下面是我需要的输出,

在此处输入图片说明

try to change this尝试改变这一点
x = (x.split('_')[0]) x = (x.split('_')[0])

Think of what your CSV output looks like, then think of what it SHOULD look like.想想你的 CSV 输出是什么样子,然后想想它应该是什么样子。

Your CSV is generated by these two loops:您的 CSV 是由这两个循环生成的:

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)

That means that anything you add to your CSV file in the second loop will be written AFTER what was added in the first loop.这意味着您在第二个循环中添加到 CSV 文件的任何内容都将在第一个循环中添加的内容之后写入。

I can think of two ideas to solve this from the top of my head:我可以从脑海中想到两个想法来解决这个问题:

  1. Somehow fuse the loops into one, thus generating each row in one loop iteration.以某种方式将循环融合为一个,从而在一次循环迭代中生成每一行。 I don't know if that works with your parameters, though.不过,我不知道这是否适用于您的参数。
  2. Don't add to the end of the CSV file, but add to the row you want to add by specifically telling the "write" function where to write.不要添加到 CSV 文件的末尾,而是通过明确告诉“写入”函数在哪里写入来添加到要添加的行。

Disclaimer: I'm not familiar with Python at all, this is just the logical source of the problem and two solutions that should work in theory.免责声明:我根本不熟悉 Python,这只是问题的逻辑来源和理论上应该有效的两个解决方案。 I do not know if either of them is practicable.我不知道他们中的任何一个是否可行。

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.我基本上保持原样,将其放入 CSV,然后读取 CSV,将列存储为列表,删除空格并将其导出。

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