DragonToes DragonToes - 3 years ago 107
Python Question

How to loop over generator and output to csv?

Very very very new to python here, so I have a basic question: I have a function that outputs generators. I need to loop over them and output to a csv.

for i in library.function(bounding box):
print (library.function2(i))


This returns several thousand unique generators. How do I output the looped info to a csv? I feel like I keep over complicating this, but I'm still learning.

Thank you!

Answer Source

open a file handle, then write to the handle:

with open('foo.csv', 'w') as f:
    for i in data.function(x,y,z):
        f.write(i)

You may need to serialize i to a string if i is an Object that does not implement __str()__ or __unicode__ methods.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download