How do I import a Python script from a sibling directory?

前端 未结 2 868
陌清茗
陌清茗 2020-12-05 06:05

Here is the directory structure:

parent_dir/
    foo_dir/
        foo.py
    bar_dir/
        bar.py

How do I import bar.py into foo.py?

相关标签:
2条回答
  • 2020-12-05 06:47

    If all occurring directories are Python packages, i.e. they all contain __init__.py, then you can use

    from ..bar_dir import bar
    

    If the directories aren't Python packages, you can do this by messing around with sys.path, but you shouldn't.

    0 讨论(0)
  • 2020-12-05 07:03

    You can use the sys and os modules for generalized imports. In foo.py start with the lines

    import sys
    import os
    sys.path.append(os.path.abspath('../bar_dir'))
    import bar
    
    0 讨论(0)
提交回复
热议问题