Search code examples
pythonlistcsvenumerate

Writing Python list to a CSV file clears the list


I'm doing some tests with lists, enumerate() method and CSV files.

I'm using the writerows() method to save an enumerate object to a .csv file. All works fine but the list / enumerate object becomes empty after the writing is done.

Why is this happening ? How can I keep the values in my list (do I have to save them in amother variable)?

I'm on Windows 10 using Python 3.6.4

Here is My Code:

import csv

b = [1,2,3,4,5,6,7,8,9,10,11,"lol","hello"]
c = enumerate(b)

with open("output.csv", "w", newline='') as myFile:
    print("Writing CSV")
    writer = csv.writer(myFile)
    writer.writerows(c)

print(list(c))

output:

>>>Writing CSV
>>>[]
>>>[Finished in 0.1s

If I preform: print(list(c)) before the writing method, c also becomes empty.

Thanks!


Solution

  • c = enumerate(b)
    

    Here c is not list but a generator, which is consumed when you iterate over it.

    You will have to create new generator every time you use it.

    If you want a permanent reference to the exhausted contents of the generator, you have to convert it to list.

    c = list(enumerate(b))