Import file from parent directory?

后端 未结 6 1958
悲哀的现实
悲哀的现实 2020-12-08 18:25

I have the following directory structure:

application
    tests
        main.py
    main.py

application/main.py contains some functions.

相关标签:
6条回答
  • 2020-12-08 18:35

    You cannot import things from parent/sibling directories as such. You can only import things from directories on the system path, or the current directory, or subdirectories within a package. Since you have no __init__.py files, your files do not form a package, and you can only import them by placing them on the system path.

    0 讨论(0)
  • 2020-12-08 18:38

    First of all you need to make your directories into packages, by adding __init__.py files:

    application
        tests
            __init__.py
            main.py
        __init__.py
        main.py
    

    Then you should make sure that the directory above application is on sys.path. There are many ways to do that, like making the application infto a package and installing it, or just executing things in the right folder etc.

    Then your imports will work.

    0 讨论(0)
  • 2020-12-08 18:43

    in python . exists for same directory, .. for parent directory to import a file from parent directory you can use ..

    from .. import filename (without .py extension)

    0 讨论(0)
  • 2020-12-08 18:50

    If you'd like your script to be more portable, consider finding the parent directory automatically:

    import os, sys
    sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    # import ../db.py
    import db
    
    0 讨论(0)
  • 2020-12-08 18:56

    To import a file in a different subdirectory of the parent directory, try something like this:

    sys.path.append(os.path.abspath('../other_sub_dir'))
    import filename_without_py_extension
    

    Edit: Missing closing bracket.

    0 讨论(0)
  • 2020-12-08 19:00

    You must add the application dir to your path:

    import sys
    sys.path.append("/path/to/dir")
    from app import object
    

    Or from shell:

    setenv PATH $PATH:"path/to/dir"
    

    In case you use windows: Adding variable to path in windows.

    Or from the command line:

    set PATH=%PATH%;C:\path\to\dir
    
    0 讨论(0)
提交回复
热议问题