'Get location of the workbook calling the script
I am trying to execute the following Python script from Excel using
Sub MacrosTrigger()
RunPython ("import MacrosTrigger")
End Sub
MacrosTrigger.py contains the following sample code
import os
import pandas as pd
import glob
import matplotlib.pyplot as plt
import matplotlib
import xlwings as xw
matplotlib.rcParams['figure.figsize'] = (18.0, 5.0)
wb = xw.Book.caller()
cwd = os.getcwd()
wb.sheets[0].range('A1').value = cwd
os.chdir('C:\\Users\\HegdeP\\Desktop\\Python Data Analysis\\PST')
os.getcwd() returns the location of the Python interpreter. For automation purposes, I would like to be able to return the location of the workbook that is calling the script. i.e. location of the wb.
Solution 1:[1]
The absolute path of an xlwings.Book
can be obtained via the fullname
attribute, so in your case wb.fullname
.
In the comments you said you were only referring to the foldername. In this case, use
foldername = os.path.dirname(wb.fullname)
Check out the docs for os.path
for lots of other useful functions to work with filenames.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |