0

Problem definition:
I am running python scripts from Excel using xlwings and I have a file that I am using in these scripts.

I used to have the path specific to my computer (ex--> C:\users\myuser\some_folder\myfile).

now I am sending these scripts to my collogues to use, and I want the path of the file to be automatically configured according to the location of the file on their machines. I tried using os package.

I tried this post and this post and finally tried moving the file in the same location and used os.getcwd() to get the working directory and concatenated with the file name to get the path.

these methods worked fine when I am running the python scripts alone (not from Excel), but When I tried running from Excel it did not work because for some reason when running python scripts from Excel the working directory changes to C:\\ProgramData\\Anaconda3\\ and no longer sees the file. also, these method (according to my understanding) uses the path of the directory from which the file is running.

they are only seeing files in C:\\ProgramData\\Anaconda3\\.
my 1st thought was to try to search for the folder name using this solution but the problem is that I do not know which location the end user will store the folder in.

What I am thinking now is find a way to locate (form this location C:\\ProgramData\\Anaconda3\\ (where python is run from Excel)) the folder which the file is stored at and from there easily grab the file path. after searching the web I did not find a suitable solution for my case.
so, is there a way to do this using os or any other package?

dsal3389
  • 658
  • 1
  • 7
  • 26
Adel Moustafa
  • 150
  • 1
  • 9
  • I think this is not a feasible idea. Why not ask user to place the file in specific directory, i.e. same directory as your excel/program file? – Dhana D. Dec 07 '22 at 10:09
  • I didn't really understand your question but would this help? `__file__`, it contains the absolute path to the current python script, `print(__file__)` – dsal3389 Dec 07 '22 at 10:15
  • @dsal3389 Thank you for commenting. I used your suggestion to find the location of the current python script and then applied to it `os.path.abspath(os.path.dirname(__file__)) + \myfile` and it worked. if you please move your comment to the answer section so I can accept it as an answer. thanks. – Adel Moustafa Dec 07 '22 at 13:19

1 Answers1

2

__file__ contains the absolute path to the executed python script without being effected by the current working directory

# example script located at /usr/bin/foo.py
print(__file__)

output:

/usr/bin/foo.py
dsal3389
  • 658
  • 1
  • 7
  • 26