Search code examples
pythonexport-to-csv

write list to csv without modules


Now I got a list of 100 items:

[['A'], ['B'], ['C'], ['B'],...]  

I need to write the list into a csv file and my expected output is like:

enter image description here

As I am not allowed to use any modules, most methods from the internet are not applicable.

Currently my output is like:

enter image description here

the code written so far is

 with open('output.csv', 'w') as f:
        f.write('id,category\n')
        for i in range(len(list)):
            f.write(str(i+1) + ',' + str(list) + '\n')

How should I modify my code to reach my expected output?


Solution

  • You need to use the index of the list in the loop

    Try this code

    lst = [['A'], ['B'], ['C'], ['B'], ['E'], ['F'], ['Y']]  
    
    with open('output.csv', 'w') as f:
        f.write('id,category\n')
        for i in range(len(lst)):
            f.write(str(i+1) + ',' + str(lst[i][0]) + '\n')
    

    Output (output.csv)

    id,category
    1,A
    2,B
    3,C
    4,B
    5,E
    6,F
    7,Y