Home > OS >  How to find the path of a specific file from another folder
How to find the path of a specific file from another folder

Time:12-09

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?

CodePudding user response:

__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
  • Related