简体   繁体   English

如何获取目录以从 Python 中的另一个文件打开文件

[英]How to get the directory to open a file from another file in Python

Having this directory structure.有这个目录结构。 fileOpener.py opens the testfile.txt . fileOpener.py打开testfile.txt And fileCallingFileOpener.py , fileCallingFileOpener2.py and fileCallingFileOpener3.py call a method from fileOpener.py that opens testfile.txt .并且fileCallingFileOpener.pyfileCallingFileOpener2.pyfileCallingFileOpener3.py fileOpener.py一个打开testfile.txt的方法。 What would be the correct path written in fileOpener.py so that it always work?fileOpener.py编写的正确路径是什么,以便它始终有效? Even in other computers.即使在其他计算机中。

\parentDirectory
    \subfldr1
        -fileOpener.py
        -testfile.txt
    \subfldr2
        -fileCallingFileOpener.py
    \subfldr2
        -fileCallingFileOpener2.py
    -fileCallingFileOpener3.py

I am asking something like:我在问类似的问题:

os.path.join("..", "subfldr1", "testfile.txt")

But make it generic so it doesn't depends from where you call it.但是让它通用,所以它不取决于你在哪里调用它。

You could try to get the location of the fileOpener module using __file__ and then make the path relative to that:您可以尝试使用__file__获取fileOpener模块的位置,然后使路径相对于该路径:

# parentDirectory/subfldr1/fileOpener.py
from pathlib import Path


def read_file():
    file_path = Path(__file__).parent / "testfile.txt"

    with file_path.open("r", encoding="utf-8") as file:
        ...

An alternative is to just use an absolute path to a file created in a temp directory, if necessary, or configurable by the end user with, for example, an environment variable.另一种方法是仅使用在临时目录中创建的文件的绝对路径,如有必要,或由最终用户使用例如环境变量进行配置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM