1

Happy NYE! Hopefully this is the last question of the year from me. I am trying to create a dynamic excel path for python to extract various excel files based on the date, type parameters, etc.

I have created below parameters which I can change base on the file I am trying to retrieve:

date = input() [assign '201912']
type = input() [assign 'abc']

I am trying to figure out a way to incorporate these into the file directory I am asking python to read such that it returns the same result as below:

import pandas as pd
sheet=pd.ExcelFile(r'C:\Information\Management\201912\abc\abc Template 201912.xlsm')

Have tried few different ways but cant seem to get it to work. Any suggestions on this?

Thank you very much!

1
  • I tried sheet=pd.ExcelFile(r'C:\Information\Management\%s\abc\abc Template 201912.xlsm'%date) which works but how would you go about this if you have more than one value to replace Commented Dec 31, 2019 at 16:23

1 Answer 1

1

You can format it with the % sign like in Python 2 (not recommended):

path = r'C:\Information\Management\%s\%s\%s Template %s.xlsm' % (date, type, type, date)

The Pythonic way in Python 3 is to use str.format:

path = r'C:\Information\Management\{}\{}\{} Template {}.xlsm'.format(date, type, type, date)

Or with named parameters:

path = r'C:\Information\Management\{date}\{type}\{type} Template {date}.xlsm'.format(date=date, type=type)

Starting with Python 3.6, you can also use f-strings:

path = f'C:\\Information\\Management\\{date}\\{type}\\{type} Template {date}.xlsm'
sheet = pd.read_excel(path)
Sign up to request clarification or add additional context in comments.

2 Comments

thanks so much for answering! I am using python 3 unfortunately. What would be the corresponding code to make it work ?
You get find out the exact version of Python you are using by typing python --version in the command line. BTW, 3.6 is Python 3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.