模块中具有相对于调用该模块的文件的相对路径

Odg*_*Gsf 4 python module class path

假设我有当前的文件结构:

  • 应用程序\模块\module.py
  • 应用程序\模块\somefile.txt
  • 应用程序\脚本\script.py
  • 应用程序\main.py

模块\script.py:

import sys
sys.path.append("..\\")
from modules.module import module
[...]
Run Code Online (Sandbox Code Playgroud)

主要.py:

import sys
from modules.module import module
[...]
Run Code Online (Sandbox Code Playgroud)

模块\module.py:

[...]
fileToRead="somefile.txt"
Run Code Online (Sandbox Code Playgroud)

问题是 :

  • 如果我的模块是从 main.py 导入的,则 somefile.txt 的路径应该是"modules\\somefile.txt"
  • 如果我的模块是从 script.py 导入的,则 somefile.txt 的路径应该是"..\\modules\\somefile.txt"

我不想使用绝对路径,因为我希望我的应用程序文件夹可移动。我想到了相对于根文件夹的路径,但我不知道这是否是一个干净的解决方案,而且我不想用多余的东西污染我的所有脚本。

有没有一个干净的方法来处理这个问题?

mar*_*eau 5

我不确定您在做什么,但由于somefile.txt与 位于同一文件夹中,因此您可以使用其预定义属性module.py使其相对于模块的路径:__file__

import os
fileToRead = os.path.join(os.path.dirname(__file__), "somefile.txt")
Run Code Online (Sandbox Code Playgroud)