davork
davork

Reputation: 179

how to pass a variable value to a file naming string in xlsxwriter

I am trying to get the value from a variable and pass it into xlsxwriter filename.

Here is my code:

company_code = 'XXX'
workbook = xlsxwriter.Workbook('Funddata_'+(company_code)+'_%s.xlsx' %timestr)
worksheet = workbook.add_worksheet()

My output file name I am getting is Funddata__201810.xlsx but I am trying to get Funddata_XXX_201810.xlsx

Upvotes: 2

Views: 1160

Answers (1)

Phil
Phil

Reputation: 3746

You can use % formatting, which you've tried to do already.

company_name = "XXX"
filename = 'Funddata_%s_%s.xlsx' % (company_name, timestr)
workbook = xlsxwriter.Workbook(filename)

OR

You can use f-strings if you're in python 3.6+. F-strings allow you to insert a variable directly into a string using curly braces

filename = f'Funddata_{company_name}_{timestr}.xlsx' # note f before opening quote
print(filename) # prints Funddata_XXX_201810.xlsx

Upvotes: 6

Related Questions