![](/img/trans.png)
[英]How can I make my script run from executable python file on Unix if it uses functions imported from other files? (ModuleNotFoundError)
[英]How can I run a python file that uses other folders with files, without using the computer's path?
我的目标是运行一个 python 文件,该文件使用与 python 文件位于同一文件夹中的文件夹中的文件,但不考虑计算机的路径。
我现在的情况是我必须在我的代码中定义路径,如:C:/Users/path/to/files/etc。
理想的情况是,如果我可以创建一个包含 python 文件的主文件夹(最好是一个 zip 文件夹),以及包含 python 文件正在使用的文件的必要文件夹。 这样我就可以将主文件夹发送给任何人,他们应该能够运行 python 文件。
我还使用 os 库中的 os.listdir(C:/path/to/folder) 函数来导入整个文件夹,但这也适用于计算机的路径。 所以需要另一种选择。
有谁知道我怎么能做到这一点或至少接近这个?
您可以使用它来获取当前 Python 文件使用的abspath
和dirname
:
this_dir = os.path.abspath(os.path.dirname(__file__))
然后您可以使用join
以独立于操作系统的方式构建您的相对路径:
some_image = os.path.join(this_dir, 'images', 'myimage.png')
你可以做这样的事情
import sys, os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
如果我理解正确,您想在位于同一目录子文件夹中的另一个文件中使用 python 脚本。 我做对了吗? 如果是,您可以将其导入为
from <folder name> import <file name>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.