python导入不同目录下的自定义模块过程解析
作者:煮不熟的鸭子 时间:2022-11-08 16:05:47
这篇文章主要介绍了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
三、运行结果
来源:https://www.cnblogs.com/zhuanjiao/p/11668586.html
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
MySQL大量脏数据如何只保留最新的一条(最新推荐)
![](https://img.aspxhome.com/file/2023/8/88498_0s.jpg)
JS 中对象equals方法的实现
python 实现的车牌识别项目
![](https://img.aspxhome.com/file/2023/5/85155_0s.png)
python实现自动登录人人网并访问最近来访者实例
vue+elementui通用弹窗的实现(新增+编辑)
![](https://img.aspxhome.com/file/2023/7/139697_0s.png)
基于Python编写一个有趣的进程勾选器(Process Selector)
![](https://img.aspxhome.com/file/2023/6/133476_0s.png)
asp获取文件md5值
pandas按照列的值排序(某一列或者多列)
Python内存映射文件读写方式
Python爬虫使用脚本登录Github并查看信息
![](https://img.aspxhome.com/file/2023/9/83899_0s.png)
JavaScript ES6中const、let与var的对比详解
JS预览图像将本地图片显示到浏览器上
PHP中类静态调用和范围解析操作符的区别解析
python实现在函数中修改变量值的方法
MySQL中基本的多表连接查询教程
Python写代码的七条重要技巧介绍
![](https://img.aspxhome.com/file/2023/7/88847_0s.jpg)