简体   繁体   中英

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

Having this directory structure. fileOpener.py opens the testfile.txt . And fileCallingFileOpener.py , fileCallingFileOpener2.py and fileCallingFileOpener3.py call a method from fileOpener.py that opens testfile.txt . What would be the correct path written in fileOpener.py so that it always work? 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:

# 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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