Search code examples
python-3.xfilemodulepackageinit

Reading a file within module


I'm struggling with - I think - a very simple problem.

I'm developing a custom package with a structure like this:

mypackage
|      |-> __init__.py
|      |-> module1.py
|      |-> module2.py
|      |-> module3.py
|      |-> externalfile.xml

The external file is read by a fuction in module1.
I can easily and obviously do it if I launch module1 in terminal. But when I try to launch that function within another script, I have a FileNotFoundError traceback.

My question is: why in this situation I can't be able to open a file that lives witin the package itself?

# module1.py

[...]
def myfunction():
    with open('externalfile.xml', 'r') as fh:
        xml = fh.read()
    return xml
# __init__.py

import mypackage.module1
[...]
# myOtherScript.py

from mypackage import module1

[...]
script = module1.myfunction()

Error:

Traceback (most recent call last):
  File --myOtherScript.py--, line xx, in <module>
    from mypackage import module1
  File "-\Programs\Python\Python310\lib\site-packages\mypackage\__init__.py", line xx, in <module>
    with open('exeternalfile.xml', 'r') as fh:
FileNotFoundError: [Errno 2] No such file or directory: 'externalfile.xml'

Solution

  • # module1.py
    
    import os
    
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))  # Returns the absolute path to your package folder
    
    def myfunction():
        with open(os.path.join(BASE_DIR, "externalfile.xml"), 'r') as fh:
            xml = fh.read()
        return xml