【问题标题】:How to know the directory of folder where a file import b file but get the answer from b file?如何知道a文件导入b文件但从b文件中得到答案的文件夹目录?
【发布时间】:2020-03-26 15:45:47
【问题描述】:

目标

我想获取正在导入另一个文件(a.py)的目录文件(b.py)。我知道我可以在运行 b.py 时使用 os path pkg 来获取它,但我不知道如何在 a.py 中设置函数来获取答案。示例如下:

文件结构

--a_folder
  -- a.py
--b_folder
  -- b.py

b.py 导入 a.py 。 a.py详情如下:

a.py 

def import_dir():
    # print the directory of file(b.py) which imports a.py.
    # the type of output is string.


b.py
import sys 
sys.append(../a_folder)
from a import import_dir  

import_dir # when run this line, it will get the directory of file(b.py).

【问题讨论】:

  • 那么,您希望从“a”中的函数调用内部获取导入其他 Python 文件“a”的 Python 文件“b”的目录路径?你能告诉使用这里的目标是什么吗?因为可能有一种更简单的方法可以实现您想要做的事情(这仅在特定情况下才有可能)。
  • 你为什么不把它作为参数 - def import_dir(folder):

标签: python python-3.x


【解决方案1】:

您在寻找os.path.dirname(__file__) 吗?

【讨论】:

  • 我不这么认为,因为这让他们获得了 当前 文件的路径,而他们正在询问执行导入的文件的路径。跨度>
【解决方案2】:
a.py 
import os

def import_dir(path=os.getcwd()):
    # print the directory of file(b.py) which imports a.py.
    # the type of output is string.
    print(path)


b.py
import sys 
sys.append(../a_folder)
from a import import_dir  

import_dir # when run this line, it will get the directory of file(b.py).

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-04
    • 2011-07-22
    • 2014-02-02
    • 1970-01-01
    • 2022-08-06
    • 1970-01-01
    • 2016-03-29
    相关资源
    最近更新 更多