简体   繁体   中英

importing python module using relative name

I'm having difficultly with important a python module from another folder. Here's how my folder looks currently

foldername/
    __init__.py
    A/
        __init__.py
        spam.py
        grok.py
    B/
        __init__.py
        foo.py

I'm trying to import the functions and classes from the grok.py file into the foo.py in B. This is how my foo.py looks like

from ..A.spam import func 

However, I get the following error:

ValueError: attempted relative import beyond top-level package

Could somebody help me? I don't understand where I'm going wrong

You can't use '..' like you do on the command line. You have to add your 'A' folder to your Python path. You can use sys.path.append('/dir/of/A') and then from A.spam import func

Instead of using sys.path you could also add a *.pth-file to your python or anaconda "site-packages"-folder which contains the path to the folder "A". Import via from A.spam import func as @bikemule already proposed.

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