这篇文章主要介绍了python导入不同目录下的自定义模块过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

一、代码目录结构

自定义的模块在Common包下,Study文件下SelectionSort.py文件导入自定义的模块

二、源码

2.1:SelectionSort.py文件

python导包默认是从sys.path中搜索的。

  sys.path结果如下:['D:\\PyCharm\\source\\Study', 'D:\\PyCharm\\source', 'D:\\PyCharm\\source\\venv\\Scripts\\python36.zip', 'D:\\Python\\Python36\\DLLs', 'D:\\Python\\Python36\\lib', 'D:\\Python\\Python36', 'D:\\PyCharm\\source\\venv', 'D:\\PyCharm\\source\\venv\\lib\\site-packages', 'D:\\PyCharm\\source\\venv\\lib\\site-packages\\setuptools-40.8.0-py3.6.egg', 'D:\\PyCharm\\source\\venv\\lib\\site-packages\\pip-19.0.3-py3.6.egg']

从结果中可以看到,并没有Common,也就是说直接是不能导入Common下的模块的(即:不能写成from CreateData import createData)。处理方式如下:

2.1.1:

  from Common.CreateData import createData
  from Common.Swap import swap

2.1.2

  sys.path.append('../Common')
  from CreateData import createData
  from Swap import swap

说明:网上大多数是第二种,将自定义模块路径加入到sys.path中,未找到第一种,这个可能是版本差异?前辈们用的python2.x,不支持包名.模块名?我用的是python3.6.8

import sys
sys.path.append('../Common') #模块所在目录加入到搜素目录中
from CreateData import createData
from Swap import swap


def selectSort(lyst):
  i = 0
  while i < len(lyst) - 1:
    minindex = i
    j = i + 1
    while j < len(lyst):
      if lyst[j] < lyst[minindex]:
        minindex = j
      j += 1
    if minindex != i:
      swap(lyst, i, minindex)
    i += 1
    print(lyst)
selectSort(createData())

2.2:CreateData.py文件

 def createData():
   return [23, 45, 2, 35, 89, 56, 3]

2.3:Swap.py文件

 def swap(lst, i, j):
   temp = lst[i]
   lst[i] = lst[j]
   lst[j] = temp

三、运行结果