获取文件路径 Python 中导入模块的文件的相对路径

Get Path of File Relative Path of File that Imported Module in Python

我在 my_program.py 中有此代码:

from my_module import do_stuff_with_file

do_stuff_with_file("hi.txt")

这是my_module.py:

def do_stuff_with_file(fileName):
    print(fileName)
    # do stuff with the file

my_module.pymy_program.py 不在同一目录时,会出现找不到文件的错误。使用此代码 (my_module.py).

解决了此问题
def do_stuff_with_file(fileName):
    fileName = os.path.join(os.path.dirname(sys.modules['__main__'].__file__), fileName)
    print(fileName)
    # do stuff with file

my_program.py 由不同目录中的文件导入时会出现此问题。

我该如何解决这个问题?

给定以下文件层次结构:

stack_overflow/
├─ q67993523/
   ├─ my_module/
   │  ├─ __init__.py
   ├─ 67993523.py
   ├─ hi.txt

文件内容如下:

# 67993523.py
from my_module import do_stuff_with_file

do_stuff_with_file("hi.txt")
# my_module/__init__.py
def do_stuff_with_file(filename):
    print(f"{filename!s} content is :")
    with open(filename, "rt") as file:
        print(file.read())

和文件 hi.txt :

Hello !

当我 运行 C:\path\to\python.exe C:/stack_overflow/q67993523/67993523.pyq67993523 的路径包含在我的 PYTHONPATH 中)时,我的当前目录是 q67993523/,我得到:

hi.txt content is :
Hello !

但是如果我将当前目录更改为 q67993523/my_module/ 并执行完全相同的命令,我会得到:

hi.txt content is :
Traceback:
[...]
FileNotFoundError: [Errno 2] No such file or directory: 'hi.txt'

因为相对于当前工作目录 q67993523/my_module/ 没有文件 hi.txt,文件将是 ../hi.txt.

我认为你正在做的是 XY problem.

的实例

您想要实现的是找到一个给出文件名而不是位置的文件。这很难做到,容易出错,并且会包含很多 hacks 才能工作。
我认为这 实际上 不是您想做的。我想您要做的不是搜索文件,而是使用它们。所以你不应该失去他们所在位置的宝贵信息。

例如,在您的主脚本中(我的是 67993523.py),您知道该文件就在那里,在同一目录中。但是如果你只是发送hi.txt,因为函数不知道调用她的代码的文件位置,它不知道去哪里搜索文件。
相反,给出完整文件位置,即绝对路径。

如果我将主脚本更改为:

# 67993523.py
from pathlib import Path

from my_module import do_stuff_with_file

the_directory_of_this_pyfile = Path(__file__).parent
do_stuff_with_file((the_directory_of_this_pyfile / "hi.txt").absolute())

和 运行 我的当前目录是 q67993523/,我得到:

C:\stack_overflow\q67993523\hi.txt content is :
Hello !

当我将当前目录更改为 q67993523/my_module/ 时,我得到了同样的结果:

C:\stack_overflow\q67993523\hi.txt content is :
Hello !

不同之处在于,在您的脚本中,hi.txt 文件名假设您当前的工作目录是 q67993523/。如果你有一个不同的当前工作目录(因为 Pytest,因为 运行 将脚本放在你想要的任何地方,...请参阅@tdelaney 的评论)然后没有 ./hi.txt 文件,所以它会失败。

我鼓励你学习 current working directory 以及如何表达 current Python file directory.