John wrote:
>         #Set up writer
>         import csv
>         vardict=vars()
>         for var in vardict:
>                 if var=='allcum' or var=='alldhdt':
>                         outfile=in_path+'/'+dataset+'_'+str(var)+'.csv'
>                         writer = csv.writer(open(outfile, "wb"))
>                         writer.writerows(var)
>  
> I'm trying to do the above, but of course get an error because vardict 
> is only referencing vars(), thus changes size... also, I tried 
> vardict=[vars()], but this fails as well??

I'm not too clear what you are trying to do here. Do you want the values 
of the variables allcum and alldhdt?

vars() gives you a dict whose keys are varible names and values are, 
well, the values. I think you are trying to write the contents of allcum 
to a file with allcum in the name?

You could do it with vars like this:

         for var in ['allcum', 'alldhdt']:
                 outfile=in_path+'/'+dataset+'_'+var+'.csv'
                 writer = csv.writer(open(outfile, "wb"))
                 writer.writerows(vars()[var])

or you could iterate a list of name, value tuples directly:

         for name, value in [('allcum', allcum), ('alldhdt', alldhdt)]:
                 outfile=in_path+'/'+dataset+'_'+name+'.csv'
                 writer = csv.writer(open(outfile, "wb"))
                 writer.writerows(value)

I think I prefer the second, even with the duplication of names; it 
feels more explicit to me.

Another alternative would be to accumulate the values in a dict with 
keys 'allcum' and 'alldhdt'. Then you would look up in that dict instead 
of in vars().

HTH,
Kent
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to