Search code examples
pythonfilepython-os

opening non-extension file with os.path.join


I might be missing a small thing but not really sure how to get rid of the problem.

Having a directory Pic_checker. In this directory I have:

Pic_checker
  --setup.py
  /src
    --app.py
  /dir_with_doc
    --doc

setup.py with entry_points={"console_scripts": ["pbl=app:main"]} bcs I wanna run it just by typing pbl

src directory with app.py with main function.

dir_with_doc directory with doc file - this file has no extension.

In this main function I have:

with open(
    os.path.join(__file__, "../../dir_with_doc/doc"),
    encoding="utf-8",
) as f:

Bcs I want to run the script with only pbl command in terminal, I need to either put aboslute paths (I don't like this) or put relative path to the app.py file with __file__ in the os.path.join function and navigate. Sadly getting error:

print(os.path.join(__file__, "../../dir_with_doc/doc"))

# /home/user/Pic_checker/src/app.py/../../dir_with_doc/doc

NotADirectoryError: [Errno 20] Not a directory: /home/user/Pic_checker/src/app.py/../../dir_with_doc/doc.

I tried opening os.path.join thing earlier (with configparser.Configparser().read() on windows) and it was working with regular files so I assume problem is with the extension (?) and my question is:

How do I make the nonextension file suitable for it? Or is there another way of reading nonextension doc file relatively to the script file? Or am I missing a small detail?

Thanks!


Solution

  • I think that to get that working you should translate the path produced from the os.path.join function in a complete existing path expanding the .. symbol that are interpretated literally instead. You can use the os.path.realpath function. So try this:

    with open(
        os.path.realpath(os.path.join(__file__, "../../dir_with_doc/doc")),
        encoding="utf-8",
    ) as f: