简体   繁体   English

如何从另一个文件夹中查找特定文件的路径

[英]How to find the path of a specific file from another folder

Problem definition:问题定义:
I am running python scripts from Excel using xlwings and I have a file that I am using in these scripts.我正在使用 xlwings 从 Excel 运行 python 个脚本,并且我有一个在这些脚本中使用的文件。

I used to have the path specific to my computer (ex--> C:\users\myuser\some_folder\myfile ).我曾经有特定于我的计算机的路径(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.我尝试使用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.我尝试了这篇文章和这篇文章,最后尝试将文件移动到同一位置并使用os.getcwd()获取工作目录并与文件名连接以获取路径。

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.当我单独运行 python 脚本(不是从 Excel)时,这些方法工作正常,但是当我尝试从 Excel 运行时,它不起作用,因为出于某种原因,当从 Excel 运行 python 脚本时,工作目录更改为C:\\ProgramData\\Anaconda3\\并且不再看到该文件。 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\\ .他们只看到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.我现在想的是找到一种方法来定位(从这个位置C:\\ProgramData\\Anaconda3\\ (其中 python 从 Excel 运行))文件存储的文件夹,并从那里轻松获取文件路径. after searching the web I did not find a suitable solution for my case.在搜索 web 后,我没有找到适合我的案例的解决方案。
so, is there a way to do this using os or any other package?那么,有没有办法使用os或任何其他 package 来做到这一点?

__file__ contains the absolute path to the executed python script without being effected by the current working directory __file__包含执行的 python 脚本的绝对路径,不受当前工作目录的影响

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

output: output:

/usr/bin/foo.py

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM