Having a relative path in a module relative to the file calling the module

浪尽此生 提交于 2019-12-12 12:32:24

问题


Let's say I have the current file structure :

  • app\modules\module.py
  • app\modules\somefile.txt
  • app\scripts\script.py
  • app\main.py

modules\script.py :

import sys
sys.path.append("..\\")
from modules.module import module
[...]

main.py :

import sys
from modules.module import module
[...]

modules\module.py :

[...]
fileToRead="somefile.txt"

The problem is :

  • If my module is imported from main.py, the path to somefile.txt should be "modules\\somefile.txt"
  • If my module is imported from script.py, the path to somefile.txt should be "..\\modules\\somefile.txt"

I don't want to use an absolute path as I want my app folder to be movable. I thought of a path relative to the root folder, but I don't know if it's a clean solution and I don't want to pollute all my scripts with redondant stuff.

Is there a clean way to deal with this ?


回答1:


I'm not sure what all you're doing, but since somefile.txt is in the same folder as module.py, you could make the path to it relative to the module by using its predefined __file__ attribute:

import os
fileToRead = os.path.join(os.path.dirname(__file__), "somefile.txt")


来源:https://stackoverflow.com/questions/30508146/having-a-relative-path-in-a-module-relative-to-the-file-calling-the-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!