Search code examples
pythonpython-camelot

for loop to export data based on variable name


I have a list of variables I am trying to export to excel. However, I am running into an issue when creating the for loop. It seems to be using the actual value of the variable name as opposed to the variable name, which makes sense. I am also trying to name the excel file by the name of the variable, which I thought I can achieve with str(factor) in the for loop.

The variable factors of the form

factors= camelot.read_pdf('Name_pdf',flavor='stream',pages='1-2')

factors=[base_rate,territory_factor,tier_factor,protection_class_factors,age_of_home,protective_device_option,law_multi_new_construc,claim_free,new_home,tenure_aoi,prior_insurance_discount,deductible_peril,construction_type,dwelling_rating_limit,territory_adjustment_factor]


for factor in factors:
    factor.export(str(factor)+'.xlsx',f='excel')

Appreciate the assistance.


Solution

  • Since you already know the filenames, you could do something very simple like :

    factors= camelot.read_pdf('Name_pdf',flavor='stream',pages='1-2')
    factor_names=['base_rate','territory_factor','tier_factor'] # etc..
    
    for factor,factor_name in zip(factors,factor_names):
        factor.export(factor_name+'.xlsx',f='excel')