[Python] FileNotFoundError within Python package on a file in same directory as calling...

Discussão em 'Python' iniciado por Stack, Janeiro 10, 2025.

  1. Stack

    Stack Membro Participativo

    I have created a Python package, and one of the functions I have written opens a .txt file in the same directory as that function. Locally, this works fine, but when the package is built and executed a FileNotFoundError is produced.

    My package directory looks like this:

    - my_app
    |_ __init__.py
    |_ __main__.py
    |_ file.txt


    In __main__.py, I have a function that looks like this to open file.txt:

    from pathlib import Path

    def open_file():
    filepath = Path(__file__).parent / "file.txt"
    with open(filepath) as f:
    return f.read()


    When I run it locally as python -m my_app, this works fine. However, when I build it into a package and then execute it I get the following error:

    FileNotFoundError: [Errno 2] No such file or directory: '/opt/hostedtoolcache/Python/3.11.11/x64/lib/python3.11/site-packages/my_app/file.txt'

    Continue reading...

Compartilhe esta Página