phatasma-coder
phatasma-coder

Reputation: 173

How can my main Python application run a script in a subpackage which reads a file within the subpackage

I'm trying to allow foo.py to load file.txt using relative import but I'm hitting a FileNotFoundError.

 -- main.py
|
 --- submodule
       |
       |-- __init__.py
       |-- foo.py
       |-- file.txt

main.py

import os
import importlib
module = importlib.import_module('.foo', package='submodule')

foo.py

file = open("file.txt","a") 

I expected foo.py to be able to read since file.txt is in the same sub-directory. I know I can put the absolute path in foo.py but I want to know how to use the relative path in foo.py to load file.txt.

Upvotes: 0

Views: 35

Answers (1)

simkusr
simkusr

Reputation: 812

You can do this by creating current_dir variable in your foo.py file which then you can use to get the file.txt

Example of how foo.py should look:


import os

current_dir = os.path.dirname(os.path.realpath(__file__))

def read_file():
    x = os.path.join(current_dir, 'file.txt')
    with open(x, 'rb') as f:
        return f.read()

How it works, is that the first part os.path.realpath(__file__) gets you the foo.py file location in your project and the second part os.path.dirname will get the directory name where this foo.py exists. So this way you build your file path to file.txt in foo.py so that main.py could execute foo.py in order to get the content of a file.txt

And main.py:


from submodule import foo

print(foo.read_file())

Upvotes: 1

Related Questions