Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Write list of list to CSV?
#1
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
Reply
#2
I really don't know how the code in listing 2 has anything to do with the output
Reply
#3
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 ############################################
Reply
#4
(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.
Reply
#5
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...")
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#6
@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 :)
Reply
#7
(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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#8
(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")
Reply
#9
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#10
(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:  ['', '', '']
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Strange behavior list of list mmhmjanssen 2 161 May-01-2024, 07:16 AM
Last Post: Gribouillis
  No matter what I do I get back "List indices must be integers or slices, not list" Radical 4 1,221 Sep-24-2023, 05:03 AM
Last Post: deanhystad
  Delete strings from a list to create a new only number list Dvdscot 8 1,576 May-01-2023, 09:06 PM
Last Post: deanhystad
  List all possibilities of a nested-list by flattened lists sparkt 1 942 Feb-23-2023, 02:21 PM
Last Post: sparkt
  Сheck if an element from a list is in another list that contains a namedtuple elnk 8 1,876 Oct-26-2022, 04:03 PM
Last Post: deanhystad
Question Keyword to build list from list of objects? pfdjhfuys 3 1,594 Aug-06-2022, 11:39 PM
Last Post: Pedroski55
  Split a number to list and list sum must be number sunny9495 5 2,331 Apr-28-2022, 09:32 AM
Last Post: Dexty
  How to check if a list is in another list finndude 4 1,862 Jan-17-2022, 05:04 PM
Last Post: bowlofred
  Different out when using conda list and pip list Led_Zeppelin 1 4,079 Jan-14-2022, 09:30 PM
Last Post: snippsat
  Use one list as search key for another list with sublist of list jc4d 4 2,185 Jan-11-2022, 12:10 PM
Last Post: jc4d

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020