vendredi 18 septembre 2020

What's the pythonic way to read in one or another specific sheetname using read_excel

I have a project where I am reading and graphing financial information of companies where the information is entered and stored in .ods format spreadsheets. the data is read into a pandas dataframe using the odfreader in pd.read_excel().

I am in the process of expanding the scope and amount of detail being entered into the spreadsheets and thus have 2 different versions; the original and the new.

The original file had a sheet with just the basic summary of the company's financial information whereas the newer version has an expanded amount of data in the summary sheet. They have different names so I know at a glance which information they will contain and if it needs to be updated.

I am currently using the following code to see which version of the summary sheet exists, and load the one that does exist.

try:
    financial_summary_sheet = pd.read_excel(financial_history_file, 'Financial Summary', header=1, engine='odf')   # new format

except:
    financial_summary_sheet = pd.read_excel(financial_history_file, 'Base Financials', header=1, engine='odf') # old format

It works, but is there a way to do this in an if / else statement?

Similar to checking if a file exists and reading it;

if financial_history_file.is_file():    # Load the financial history file for the security if it exists
    # if it does exist, read file and do many things with the data...

or checking if a column exists in the sheet;

if 'Notes' not in financial_summary_sheet:  # check if Notes column exists in sheet
    # if it doesn't, make notes column to explain the things of many...

I can't find a similar way to determine the sheet name exists using an if/else statement.

Is there a way to do this other than the try/except method?

Aucun commentaire:

Enregistrer un commentaire