Python Forum

Full Version: Write list of list to CSV?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
Hi, I would like to ask on how we can write these set of list which has list in it?

Target output on csv is like this(attached).
[Image: mqc9TnC]

opo = ['device1', 'device1', 'device1']
intfname = [['HundredGigE0/2/0/0', 'HundredGigE0/2/0/0.242', 'HundredGigE0/2/0/0.244 l2transport', 'HundredGigE0/2/0/1', 'HundredGigE0/2/0/0.244'], ['TenGigabitEthernet1/1/0.138'], ['TenGigE0/1/0/15']]
descname = ['0/2/0/0info1', '0/2/0/0.242info2', '0/2/0/0.244info3']

## EXPORT AS CSV
with open('intlist.csv', 'w', newline='') as updatecsv:
    write = csv.writer(updatecsv, delimiter=',',lineterminator='\n')
    write.writerows(zip(opo,intfname,descname))
updatecsv.close()
print ("Done...")
my current out is like:
Column1        C2                  C3  
device1     [int1,int2,int3]     [desc1, desc2, desc3]
device2     [int1,int2]          [desc1, desc2]
what method should I use to achieve this?

Thanks
I really don't know how the code in listing 2 has anything to do with the output
If all you are trying to do is formatted print, replace values in list below with actual values (programmatically)
and they will format properly **NOTE** requires python 3.6 or newer as it uses f-string
head = '###########[b]Column[/b]####################'
foot = '############################################'
displaylist = [
    ['#', 'Device1', 'Int1', 'description', 'remarks'],
    ['R', '', 'Int2', 'description', ''],
    ['O', '', 'Int3', 'description', ''],
    ['W', 'Device2', 'Int1', 'description', 'remarks'],
    ['#', '', 'Int2', 'description', '']
]

print(head)
for item in displaylist:
    print(f'{item[0]:3}{item[1]:10}{item[2]:9}{item[3]:15}{item[4]:8}')
print(foot)
output:
Output:
###########[b]Column[/b]#################### # Device1 Int1 description remarks R Int2 description O Int3 description W Device2 Int1 description remarks # Int2 description ############################################
(Feb-24-2019, 01:28 AM)Larz60+ Wrote: [ -> ]I really don't know how the code in listing 2 has anything to do with the output

Yep, not that much. but seen that there a method that they compile those list. I just note that I have list inside a list. Others manipulate din on exporting part but I'm still grasping on how to do that.

Thanks for this, I have modified the question and attached an image of what im trying to achieve. Apologies for the confusion.
the easiest way is to make also opo and descname list of lists.
Then use itertools.zip_longest
import itertools
import csv
opo = ['device1', 'device1', 'device1']
intfname = [['HundredGigE0/2/0/0', 'HundredGigE0/2/0/0.242', 'HundredGigE0/2/0/0.244 l2transport', 'HundredGigE0/2/0/1', 'HundredGigE0/2/0/0.244'], ['TenGigabitEthernet1/1/0.138'], ['TenGigE0/1/0/15']]
descname = ['0/2/0/0info1', '0/2/0/0.242info2', '0/2/0/0.244info3']

opo = [[ele] for ele in opo]
descname = [[ele] for ele in descname]
 
## EXPORT AS CSV
with open('intlist.csv', 'w', newline='') as updatecsv:
    write = csv.writer(updatecsv, delimiter=',',lineterminator='\n')
    for cols in zip(opo,intfname,descname):
        rows = itertools.zip_longest(*cols, fillvalue='')
        write.writerows(rows)
updatecsv.close()
print ("Done...")
@buran Awesome, Thank you very much. But, Seems like I have unlocked a new problem lol... After running this from my original file which Im working, It's not writing any data on the CSV, maybe u have encountered/ any idea with this?

Although I have isolated the export csv and verified its working.

Question regaing the given code.
opo = [[ele] for ele in opo] - What we did here is we create a specifically significant variable(ELE) which we put the opo list into the ele list.
since this is specifically significant with opo it self, we can still use the ELE as naming to others.

then we put the list into zip and this itertools.izip_longest(*iterables[, fillvalue]) is fill all the blank data a loop until find the longest match/value.

Again Thanks :)
(Feb-24-2019, 07:58 AM)searching1 Wrote: [ -> ]After running this from my original file which Im working, It's not writing any data on the CSV, maybe u have encountered/ any idea with this?
I am not sure I understand this

(Feb-24-2019, 07:58 AM)searching1 Wrote: [ -> ]opo = [[ele] for ele in opo] - What we did here is we create a specifically significant variable(ELE) which we put the opo list into the ele list.

we use list comprehension. ele is just a variable that we used to convert the list to list of lists. we don't actually care about it, so we can reuse it in the list coprehension used to turn descname to list of lists
opo = [[ele] for ele in opo]
is same as
new_opo = []
    for ele in opo:
        new_opo.appned([ele])
opo = new_opo[:]
(Feb-24-2019, 07:58 AM)searching1 Wrote: [ -> ]then we put the list into zip and this itertools.izip_longest(*iterables[, fillvalue]) is fill all the blank data a loop until find the longest match/value.

it's same as zip, however if some of the iterables are shorter than others, it will use fillvalue to work as if they were equal length
(Feb-24-2019, 08:17 AM)buran Wrote: [ -> ]
(Feb-24-2019, 07:58 AM)searching1 Wrote: [ -> ]After running this from my original file which Im working, It's not writing any data on the CSV, maybe u have encountered/ any idea with this?
I am not sure I understand this

There no data after running the script. no trace or anything will running. It's just no data can be seen once you open the csv file.

Posting my config. maybe you can see something unusual. Thanks

import re, base64, os, sys, subprocess, csv, itertools

with open('list.txt') as csvfile:
    rilist = csv.reader(csvfile, delimiter=',')
        
#Put the data from excel here
    rtrlist = []
    intlist = []
    ilist =[]
    dlist = []
    blist = []
        
#Action - Put the data from excel to variable[list]
    for col in rilist:
        rtr = col[0]
        intf = col[1]

        rtrlist.append(rtr)
        intlist.append(intf)
##    csvfile.close()
##    print(rtrlist,"\n",intlist)

    #Change Directory
    os.chdir("/rs/configs")
    print("pwd=%s" % os.getcwd())

    ## START OF THE LOOP ##
    for a,b in zip(rtrlist, intlist):
        srtr = a.strip()
        sint = b.strip()
        subint = re.sub("\d+\/*", "", sint)
        print ("Processing.... ",srtr,sint)
        proc = subprocess.Popen(("grep", "-A11", "interface %s"%sint, srtr), stdout = subprocess.PIPE)  
        lbl = proc.communicate()[0]
        teststr = lbl.decode()
        print (teststr)
        
        #SEARCH INTERFACES
        ipat = re.findall(r"(?P<intrfname>%s+\d+\/.*)" %subint, teststr)
        ilist.append(ipat)
        print ("List of Interface: \n",ipat)

        #SEARCH INTERFACE DESCRIPTION
        dpat = re.findall("(?<=description\s)([A-Za-z0-9]+\;.*)", teststr)
##        dpat = ','.join(ddpat)
        dlist.append(dpat)
        print ("\nDescription: ",dpat)

        #GET BUNDLE ID / CHANNEL GROUP
        bbpat = re.findall("(?<=bundle id\s)+\d+", teststr)
        bpat = ','.join(bbpat)
        blist.append(bpat)
        print ("\nBundled: ",bpat)

print ("\nRTR List: ",rtrlist)
print ("\nINT List: ",ilist)
print ("\nDESC List: ",dlist)
print ("\nBUN List: ",blist)

rtrlist = [[ele] for ele in rtrlist]
dlist = [[ele] for ele in dlist]

## EXPORT AS CSV
with open('intlist.csv', 'w', newline='') as updatecsv:
    write = csv.writer(updatecsv, delimiter=',',lineterminator='\n')
    for cols in zip(rtrlist,ilist,dlist):
        rows = itertools.zip_longest(*cols, fillvalue='')
        write.writerows(rows)
updatecsv.close()
print ("\n Done...csv file has been updated")
what's the output from
print ("\nRTR List: ",rtrlist)
print ("\nINT List: ",ilist)
print ("\nDESC List: ",dlist)
print ("\nBUN List: ",blist)
and there is no need of line 69 updatecsv.close() - you are using with context manager so it will take care to close the file
(Feb-24-2019, 08:43 AM)buran Wrote: [ -> ]what's the output from
print ("\nRTR List: ",rtrlist)
print ("\nINT List: ",ilist)
print ("\nDESC List: ",dlist)
print ("\nBUN List: ",blist)
and there is no need of line 69 updatecsv.close() - you are using with context manager so it will take care to close the file

@buran Noted, I have removed the close csv.

Heres the print output, Though I have sanitized the desc list since it contains sensitive information. But its similar to the 1st above output.

RTR List:  ['r01.tp06', 'r02.m01', 'r01.m02']
INT List:  [['HundredGigE0/2/0/0', 'HundredGigE0/2/0/0.242', 'HundredGigE0/2/0/0.244 l2transport', 'HundredGigE0/2/0/1', 'HundredGigE0/2/0/0.244'], ['TenGigabitEthernet1/1/0.138'], ['TenGigE0/1/0/15']]
DESC List:  [['ALPHANUMERICWITHCHARAC;;;', 'ALPHANUMERICWITHCHARAC;;;', 'ALPHANUMERICWITHCHARAC;;;'], ['ALPHANUMERICWITHCHARAC;;;'], ['ALPHANUMERICWITHCHARAC;;;']]
BUN List:  ['', '', '']
Pages: 1 2