简体   繁体   中英

cannot import the module in Python

I have the following folder structure.

check_site
- test_site
    -- views.py
- app2
- app3
- modules
    -- url.py
    -- usability.py

module ulr.py contains one class inside - Url.py

class URL:
    ...

module usability.py contains one class that inherit URL class

from url import URL
class Usability(URL):
    ...

And then I have a view.py where I neen to import class Usability

from modules.url import URL
from modules.usability import Usability

And here is a problem. It gives me an error

from url import URL
ModuleNotFoundError: No module named 'url'

I've tried to change the import in usability.py to from modules.url import URL but in this case it gives the error in the usability.py

Unable to import modules.url

I've also tried from.url import URL and from check_site.modules.url import URL But these also don't work

If someone knows how to fix it, please help

Well, the problem lies here because by default Python searches for the file in the current directory but the file u want to import is not in the same directory as your program. You should try sys.path

# some_file.py
import sys
# insert at 1, 0 is the script path (or '' in REPL)
sys.path.insert(1, '/path/to/application/app/folder')

import file

This should work in most cases.

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