Search code examples
pythonpython-3.xcsvopencsv

Writing data in lists


I want to get rid of manually writing the data into a list every time and automate the process. The data would be coming from a csv file. I just want to be able to call on to the file and the data becomes part of the list so I can use that. This is what I have as my code.

lista1=['number','number','AAA','BBB','CCC','DDD','number','number','AAA','BBB','CCC','DDD','number','number','AAA','BBB','CCC','DDD']
lista2=[1,1,10,11,12,13,1,1,14,15,16,17,1,1,18,19,20,21]
lista_final = []
for i in range(len(lista1)):
    if lista1[i] == 'AAA':
        print('AAA',lista2[i])
    if lista1[i] == 'BBB':
        print('BBB',lista2[i])
    if lista1[i] == 'CCC':
            print('CCC',lista2[i])
    if lista1[i] == 'DDD':
        print('DDD',lista2[i])

Sample Data:

AAA BBB CCC DDD AAA BBB CCC DDD
10 11 12 13 14 15 16 17

Output:

AAA BBB CCC DDD
10 11 12 13
14 15 16 17

My main concern still is to get the sample data into the list instead of actually writing down the values like 'AAA' 'BBB'


Solution

  • Check out Python's csv module which provides you with tooling for easy csv-reading and -writing.

    Example from the docs for reading:

    import csv
    
    with open('eggs.csv', newline='') as csvfile:
    
        spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
    
        for row in spamreader:
    
            print(', '.join(row))
    Spam, Spam, Spam, Spam, Spam, Baked Beans
    Spam, Lovely Spam, Wonderful Spam
    

    and for writing:

    import csv
    with open('eggs.csv', 'w', newline='') as csvfile:
        spamwriter = csv.writer(csvfile, delimiter=' ',
                                quotechar='|', quoting=csv.QUOTE_MINIMAL)
        spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
        spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])