一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

python导入不同目录下自定义模块代码实例

时间:2019-11-18 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下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

三、运行结果

热门栏目