Sivo 悉见

Python父目录、子目录相互调用

匿名 · 更新于 2018/3/30

最近在使用Python的过程中经常遇到找不到该模块的问题。其中一个就是父目录子目录之间相互调用的情况。下面简单总结下。 
这里写图片描述 
我们在F:\Code文件夹下面创建一个test文件夹 
而test文件夹里面如下 
这里写图片描述 
包含两个子目录 
这里写图片描述 
a.py

def showdata():
    print("this is a")

def plus():
    a=1
    b=2
    print(a+b)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

b.py

def show():
    print("this is b")
  • 1
  • 2

从父目路test.py调用a和b

from test1.a import showdata
from test1.a import plus
from test2.b import  show

showdata()
show()
plus()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

这里写图片描述 
如何c.py想要调用另一个文件夹的a的话,需要加上sys.path.apend(“..”) 
c.py

import sys

sys.path.append("..")
from test1 import a as t

t.showdata()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

这里写图片描述