Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list write to CSV without the square brackets

Tags:

python

csv

I have this main function:

def main():
    subprocess.call("cls", shell=True)
    ipList,hostList,manfList,masterList,temp = [],[],[],[],[]
    ipList,hostList,manfList, = getIPs(),getHosts(),getManfs()
    entries = len(hostList)
    i = 0
    for i in xrange(i, entries):
        temp = [[hostList[i]],[manfList[i]],[ipList[i]]]
        masterList.append(temp) 
    with open("output.csv", "wb") as f:
        writer = csv.writer(f, delimiter=',')
        writer.writerows(masterList)

My current output is that it successfully writes to CSV but my objective is to remove the square brackets.

I tried using .join() method however I understand that it only takes single lists and not nested lists.

How can I achieve this given that I'm using a 3 dimensional list? Note, I intend to add more columns of data in the future.


Edit:

My current output for 1 row is similar to:

['Name1,'] ['Brand,'] ['1.1.1.1,']

I would like it to be:

Name1, Brand, 1.1.1.1,

like image 211
codaamok Avatar asked Nov 21 '25 02:11

codaamok


1 Answers

Try to remove bracket for values in temp while creating masterList, because it will be nested list. So, the code should be:

def main():
    subprocess.call("cls", shell=True)
    ipList,hostList,manfList,masterList,temp = [],[],[],[],[]
    ipList,hostList,manfList, = getIPs(),getHosts(),getManfs()
    entries = len(hostList)
    i = 0
    for i in xrange(i, entries):
        temp = [hostList[i], manfList[i], ipList[i]]
        masterList.append(temp) 
    with open("output.csv", "wb") as f:
        writer = csv.writer(f, delimiter=',')
        writer.writerows(masterList)
like image 144
Edward Samuel Avatar answered Nov 23 '25 15:11

Edward Samuel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!