简体   繁体   中英

Can't import module from different directory python

So below I have is my file structure:

/
    api.py       
    app.py       
code/
    data_api/
        weather_data/
            get_data_dir/
                get_data.py
            master_call_dir/
                master_call.py

My current problem is that I'm importing master_call.py from inside app.py I do this with the following code:

-- app.py

import sys
sys.path.append('./code/data_api/weather_data/master_call_dir')

from master_call import master_call_interface as master_call

Importing master_call itself works perfectly fine, the issue is that inside off master_call I import get_data.py . I do this with the following code:

-- master_call.py

import sys
sys.path.append("../get_data_dir")

from get_data import get_data_module

When printing out sys.path I can see ../get_data_dir inside of it but Python still isn't able to find the get_data.py file in /get_data_dir .

Does anyone know how to fix this?

(there is an __init__.py file in every directory, I removed it here for readability)

So I figured it out. The problem is while the directory of the master_call.py file is /code/data_api/weather_data/master_call the current working directory (CWD) is / since that is where app.py is located.

To fix it we simply fetch absolute file path in each python script with

current_path = os.path.dirname(os.path.realpath(__file__)).replace('\\', '/')

and pre-pend it to any file path we're appending with sys.path.append

So it'd look like this in practice:

import sys
import os
current_path = os.path.dirname(os.path.realpath(__file__)).replace('\\', '/')

sys.path.append(f'{current_path}./code/data_api/weather_data/master_call_dir')

from master_call import master_call_interface as master_call

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