pHorseSpec
pHorseSpec

Reputation: 1274

CSV WriteRow Data

I'm trying to write 2 variables to the rows in my csv. The result variable (which has 2 columns/values), and the 'itemvariable (which has just 1 value). Can I include both of these values in thewriterow` function parameter? If so, how would the syntax look? My syntax below with the comma between the two variables doesn't work.

line I'm talking about:

writer.writerow([item,result.items()[0][0],result.items()[0][1]])

All of code:

#!/usr/bin/env python

import splunklib.client as client 
import splunklib.results as results
import csv

listOfAppIDs = []
with open('filefolder/filelocation.txt', 'r') as fi:
    for line in fi:
        listOfAppIDs.append(line.rstrip('\n'))
listOfAppIDs.sort() #alphebetically sort list

HOST = "ipAddress"
PORT = 1234
USERNAME = "uName"
PASSWORD = "pWord"

startPoint = "firstAppInList" 

outputCsv = open('filefolder/filelocation.csv', 'wb')
fieldnames = ['appID', 'TotalDestinationIPAddresses', 'AverageThroughputPerMonth']
writer = csv.DictWriter(outputCsv, fieldnames=fieldnames)
writer.writeheader(); 

def connect():
    global startPoint , item

    service = client.connect(
        host=HOST,
        port=PORT,
        username=USERNAME,
        password=PASSWORD,
        autologin=True
    )   

    jobs = service.jobs
    kwargs_blockingsearch = {"exec_mode": "blocking"}

    try:
        for item in listOfAppIDs:
            if (item >= startPoint):
                searchquery_blocking = "splunkQuery"
                print item + ':'
                job = jobs.create(searchquery_blocking, **kwargs_blockingsearch) 
            for result in results.ResultsReader(job.results()):             
                writer.writerow([item,result.items()[0][0],result.items()[0][1]])#writes data underneath the column header
    except csv.Error:
        startPoint = item
        connect()

connect()
outputCsv.close()

ANSWER:

writer.writerow([item,result.items()[0][1],result.items()[1][1]])

Upvotes: 3

Views: 1889

Answers (2)

Alex
Alex

Reputation: 21766

You pass multiple fields to writerow by passing it an array. Assuming that result is an array of two elements, you could do this

writer.writerow([item,result[0],[result[1]])

or if result is an OrderedDict as per your comment, you can do this:

writer.writerow([item,result.items()[0][0],result.items()[0][1]])

Upvotes: 4

smsearcy
smsearcy

Reputation: 573

What error message are you receiving?

When using csv.DictWriter a dictionary should be passed to writerow(), not a list. Based on what I see you could use a normal csv.writer object and just call writerow() with your header row, rather than creating a dictionary for each call to writerow().

So if you initialize it like this I think it will work:

writer = csv.writer(outputCsv)
writer.writerow(fieldnames); 

Upvotes: 2

Related Questions