Screwing Up looping in Generator

Deborah Swanson python at deborahswanson.net
Mon Jan 2 19:17:00 EST 2017


> Sayth Renshaw wrote, on January 03, 2017 6:54 AM
> >
> > Hi
> >
> > This is simple, but its getting me confused.
> >
> > I have a csv writer that opens a file and loops each line of
> > the file for each file and then closes, writing one file.
> >
> > I want to alter the behaviour to be a written file for each
> > input file. I saw a roundrobin example however it failed for
> > me as you cannot get len(generator) to use a while loop on.
> > it exhausts
> >
> > should I use the same for again after the with open?
> >
> > rootobs in this code is my generator and I am already looping
> > it however
> > def data_attr(roots):
> >     """Get the root object and iter items."""
> >     for file in rootobs:
> >         base = os.path.basename(file.name)
> >         write_to = os.path.join("output",
> > os.path.splitext(base)[0] + ".csv")
> >         with open(write_to, 'w', newline='') as csvf:
> >             race_writer = csv.writer(csvf, delimiter=',')
> >             race_writer.writerow(
> >                 ["meet_id", "meet_venue", "meet_date", "meet_rail",
> >                  ...
> >                  # other categories here
> >                  ...
> >                     "jockeysurname", "jockeyfirstname"])
> >             for xml_data in roots:
> >                 ...
> >                 # parsing code
> >                         for noms in race_child:
> >                             if noms.tag == 'nomination':
> >                                 race_writer.writerow(
> >                                     [meet_id, meet_venue, meet_date,
> >                                      ...
> >                                     #parsing info removed
> >
> noms.get("jockeyfirstname")])
> >
> > Cheers
> > Sayth
>
> What's the code for your generator? And I don't see where you
> call 'next'.

I think you're expecting

        for file in rootobs

to get the next yield for you from rootobs, but unless someone corrects me, I 
don't think you can expect a 'for' statement to do that. You need to have a 
'next' statement inside your for loop to get the next yield from the generator.

But I might not understand exactly what you're asking.



More information about the Python-list mailing list