Unable to reference a excel marco file while running a juypter-notebook from another notebook

Question:

I’m trying to run a jupyter notebook file called Seg_pivot.ipynb from main.ipynb. The main.ipynb has one line of code: %run "fi/Seg_pivot.ipynb"

The current directory structure looks like the following: enter image description here

The Seg_pivot.ipynb runs a module in the MyMacro, used to style the files in the result folder. When I run the Seg_pivot.ipynb everything works. But when I run the main.ipynb, it gives a FileNotFound error: No such file: ‘mymacro.xlsm’

In the Seg_pivot.ipynb this is how I call the macro:

import xlwings as xw
wb = xw.Book("MyMacro.xlsm")
s_macro = wb.macro("Module2.styleF")
s_macro()
Asked By: M J

||

Answers:

I think putting inside your notebook Seg_pivot.ipynb near the top, the following may help:

import pathlib
%cd {pathlib.Path(__file__).parent.resolve()}

That will always set the working directory to where Seg_pivot.ipynb is in your file hierarchy when it runs.

Getting he path to the notebook file something is running it is based on here. The magic %cd command is documented here.

In your case, you may wish to reset the current working directory back in main.ipynb, too, i.e., after it runs the Seg_pivot.ipynb notebook if main.ipynb involves any paths after that.

Answered By: Wayne
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.