在模块中具有相对于调用模块的文件的相对路径 [英] Having a relative path in a module relative to the file calling the module

查看:203
本文介绍了在模块中具有相对于调用模块的文件的相对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Let's say I have the current file structure :


  • app\modules\module.py

  • app\modules\somefile.txt

  • app\scripts\script.py

  • app\main.py

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

modules\script.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:

modules\module.py :

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

问题是:


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

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

  • 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"

我不想使用绝对路径,因为我想要我的应用程序文件夹是可移动的。
我想到一个相对于根文件夹的路径,但我不知道它是一个干净的解决方案,我不想污染所有我的脚本与redondant的东西。

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 ?

推荐答案

但由于 somefile.txt module.py 在同一个文件夹中,因此可以将路径它通过使用其预定义的 __文件__ 属性相对于模块:

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")

这篇关于在模块中具有相对于调用模块的文件的相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆