Search code examples
pythonlistcsvzip

Problem trying to read back zip list into original lists


3 Months new to learning Python, thanks to all for the help. Amazing language.

Having an issue trying to read back a zip list saved to csv.

Here is how I'm writing the lists out to file..

def save_csv():
    buyall = list(zip(buycoin, buyprice, buyqty, buystatus))  
    with open('Trade Data.csv', 'wt') as myfile:
        wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
        wr.writerow(buyall)

How can I read these 4 lists back into the lists themselves when loading from file? Having trouble figuring out the format..

Regards, Jeff


Solution

  • please read comment in code

    import csv
    
    buycoin, buyprice, buyqty, buystatus = [
        (str(i), str(i)*(i+1), str(i)+'*') for i in range(4)]
    print(buycoin, buyprice, buyqty, buystatus)
    # ('0', '0', '0*') ('1', '11', '1*') ('2', '222', '2*') ('3', '3333', '3*')
    
    
    def save_csv():
        buyall = list(zip(buycoin, buyprice, buyqty, buystatus))
        print(*buyall)
        # ('0', '1', '2', '3') ('0', '11', '222', '3333') ('0*', '1*', '2*', '3*')
        with open('Trade Data.csv', 'wt') as myfile:
            wr = csv.writer(myfile)  # remove quoting
            wr.writerows(buyall)  # row's'
    
    
    def read_csv():
        with open('Trade Data.csv', 'rt') as myfile:
            data = csv.reader(myfile)
            data = [*zip(*data)]  # transpose
            return data
    
    
    save_csv()
    '''
    0,1,2,3
    0,11,222,3333
    0*,1*,2*,3*
    '''
    
    a, b, c, d = read_csv()
    print(a, b, c, d)
    # ('0', '0', '0*') ('1', '11', '1*') ('2', '222', '2*') ('3', '3333', '3*')