模块、包

什么是模块?
模块实质上就是一个python文件,它是用来组织代码的,意思是说把python代码写到里面,文件名就是模块的名称,例如:model.py model就是模块名称。
什么是包?
包,package本质就是一个文件夹,和文件夹不一样的是它有一个_init_.py文件,在python2中如果要导入其他文件夹下的文件必须有这个文件

导入模块

导入模块的本质就是把python文件拿过来执行一次,从头执行到尾
import在找python的时候:
1、先在当前目录中找
2、在环境变量中(python的环境变量)
第一种:python已经写好的模块,标准模块

import model '''导入模块'''
model.run()
model.run1()'''模块调用'''
model.run2()

第二种:从其他自己写好的文件中导入模块

from model import run,run1 可以导入多个函数,*代表所有的函数(不建议使用不易于查代码)
run() 调用函数
run1()

第三种:从其他文件夹下的文件导入模块

from day04.biji import is_float day04是文件下,biji是文件名,is_float是函数
is_float('89')
起别名:
from day04.biji import is_float as xiaoshu
from core import buy_product core是文件夹 buy_product是文件名
buy_product.buy_product() 调用文件里面的函数

模块分类

标准库:python内置的
开源模块:第三方
自定义模块:自己写的

安装模块的方式

第一种安装:命令行安装

  1. 进入python的安装路径例如;C:\python\Scripts  ,发现文件夹下游pip3.exe、pip.exe、或者easy_install.exe
  2. 把这个路径复制到环境变量path中,就可以在cmd中pip命令安装模块
    e.g:

    pip/pip3/easy_install install +模块名 例如requests
    pip list 查看安装的模块
    pip unistall + 模块名 卸载模块
    这种方式python3可以直接用,python2就必须自己下载

第二种方式安装:手动安装

  1. 先下载安装包比如:python中 requests
  2. 自己在本地解压
  3. 在解压的目录下的地址栏中直接输入CMD/cmd,然后执行python setup.py install

第三种方式安装:
pycharm中settings->Project Interpreter ->点击加号然后搜索安装

常用模块

json模块

json可用于字典和list
json和字典类似,但是json的里面只能是双引号,不能使单引号,
json串实际上就是一个字符串

dump和 dumps字典转json串
load和loads是json串转字典
带s就和字符串相关,不带s就和文件相关

json_str = {
"username":"duguanglong",
"passwd":"123456"
}
e.g:
json串转成字典
fr = open('users')
json_dict_file = json.load(fr)
json_dict = jsom.loads(json_str)

字典转成字符串
D = {
"admin":{
"password":"123456",
"money":"8000"
},
"duguanglong":{
"password":"123456",
"money":"8000"
}
}

fw = open('users.json','a+')
dict_str = json.dumps(D)
res = json.dumps(dict,ensure_ascii=False) #,ensure_ascii=False限制不能转成unicode
dict_str_file = json.dump(D,fw)

常用模块

os,sys模块

os

import os
print(os.getcwd()) 取当前的工作目录
os.chmod("/usr/local",7)** 给文件加权限
print(os.chidir(r"e:\byz\cod")) 更改当期那目录
print(os.curdir) 当前目录
print(os.pardir) 父目录
print(os.markdirs(r"/usr/hehe/hehe1")) 递归创建文件夹,父目录不存在时创建父目录
print(os.markdir('tttt')) 创建文件夹
print(os.removedirs(r"/usr/local")) 递归删除空文件夹
print(os.rmdir('local')) 删除空文件夹
print(os.remove('test')) 删除文件
print(os.listdir('.')) 列出目录下的所有文件列表形式
os.rename('test','test1') 重命名
os.system(cmd)执行系统命令 os.system('>access.logs') 用来清空日志,能够执行命令但是不能返回结果执行成功返回0不成功1
os.popen('ipconfig').read() 执行系统命令 能够获取结果
print(os.sep) 当前系统的路径分隔符
print(os.linesep)当前系统的换行符
print(os.pathsep)当前系统环境变量的分隔符
print(file) __file__代表当前文件
print(os.path.abspath(file)) 获取绝对路径
print(os.path.dirname(file))获取父目录
print(os.path.exists("/usr/local/test.txt")) 判断一个文件是否存在
print(os.path.isfile(file)) 判断是不是一个文件
print(os.path.isdir(file)) 判断是不是一个文件夹
print(os.path.join('usr','local','a.py')) 拼接成一个路径
print(os.envrion) 当前操作系统的环境变量
**print(os.path.split(file)分割路径和文件名
print(os.path.basename("/usr/local")) # 获取最后一级,如果是文件显示文件名,如果是目录显示目录名
print(os.path.isabs(".")) # 判断是否是绝对路径
print(os.path.isdir("/usr/local")) # 是否是一个路径
print(os.path.join("/root", 'hehe', 'a.sql')) # 拼接成一个路径
print(os.path.getatime("len_os.py")) # 输出最近访问时间
print(os.path.getmtime("len_os.py")) # 输出最近访问时间
print(os.path.split(file)分割路径和文件名

sys

import sys
sys.argv 命令行参数list,print(sys.argv)#获取后面传入的参数
E:\byzzuoye\duguanglong_lib\day06>python test2.py wjx cxh
第一个下标就是当前的这个python文件
['test2.py', 'wjx', 'cxh']

sys.exit(n) 退出程序,正常退出是exit(0)
sys.version 获取Python解释程序的版本信息
sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform 返回操作系统平台名称
sys.stdout.write('please:') # 向屏幕输出一句话
val = sys.stdin.readline()[:-1] # 获取输入的值

random

import random
random .random() 随机浮点数,默认0-1 不能指定范围
random.randint(1,20) 随机整数
random.ranrange(1,20) 产生一个随机range
print(random.choice('adafs')) 随机取一个元素
print(random.sample("hello",2)) 从序列总随机取几个元素,返回一个list
print(random.uniform(1,9)) 取随机浮点数可以指定范围
print(random.shuffle) 重新洗牌,打乱顺序

time&datetime模块

time和datetime模块主要用于操作时间
时间有三种表示方式:时间戳、格式化时间、时间元祖

import time,datetime
print(time.timezone)#和标准时间相差的时间,单位是s
print(time.time())#获取当前时间戳,从unix到现在过去了多少秒
time.sleep(1)#休息几秒
print(time.gmtime())#把时间戳转换成时间元组,如果不传的话,默认取标准时区的时间戳
print(time.localtime())#把时间戳转换成时间元组,如果不传的话,默认取当前时区的时间戳
print(time.mktime(time.localtime()))#把时间元组转换成时间戳
print(time.strftime("%Y%m%d %H%M%S"))#将时间元组转换成格式化输出的字符串
pring(time.strptime('%Y%m%d %H%M%S),time.gmtime(time.time())) #将时间戳转化成格式化输出
print(time.strptime("20160204 191919","%Y%m%d %H%M%S"))#将格式化的时间转换成时间元组
print(time.struct_time)#时间元组
print(time.asctime())#时间元转换成格式化时间
print(time.ctime())#时间戳转换成格式化时间
print(datetime.datetime.now())#当然时间格式化输出
print(datetime.datetime.now()+datetime.timedelta(3))#3天后的时间
print(datetime.datetime.now()+datetime.timedelta(-3))#3天前的时间
格式化输出:
res = datetime.datetime.now()+datetime.timedelta(3)
new_res=res.strftime("%Y%m%d%H%M%S")
print(new_res)

hashlib模块

import hashlib

MD5

m = hashlib.md5() 这是一个对象
m.update(b'hello') b代表bytes字符串转成字节,没有直接返回None
m.update(bytes(hello,encoding ='utf-8')) # 吧字符串转成字节,必须加encoding
print(m.digest()) 2进制形式输出
print(m.hexdigest()) 16进制形式输出

e.g:

def md5_passwd(str,SALT='123456'):
#SALT="!@#$%^&*(" salt是盐值
str =str+SALT
md = hashlib.md5()
md.update(str.encode())
return md.hexdigest().upper()

sha1

hash = hashlib.sha1()
hash.update('admin')
print(hash.hexdigest())

sha256

hash = hashlib.sha256()
hash.update('admin')
print(hash.hexdigest())

sha384

hash = hashlib.sha384()
hash.update('admin')
print(hash.hexdigest())

sha512

hash = hashlib.sha512()
hash.update('admin')
print(hash.hexdigest())

未完待续......

python-笔记(六)模块操作以及常用模块简介的更多相关文章

  1. Python的高级文件操作(shutil模块)

    Python的高级文件操作(shutil模块) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 如果让我们用python的文件处理来进行文件拷贝,想必很多小伙伴的思路是:使用打开2个 ...

  2. ansible笔记(5):常用模块之文件操作(二)

    ansible笔记():常用模块之文件操作(二) 文件操作类模块 find模块 find模块可以帮助我们在远程主机中查找符合条件的文件,就像find命令一样. 此处我们介绍一些find模块的常用参数, ...

  3. ansible笔记(4):常用模块之文件操作

    前文中,我们已经介绍了怎样使用模块,而且我们知道,ansible有很多模块,每个模块都有自己的功能,"模块"涉及到的方向比较多,所以对于个人来说,并没有必要了解所有的模块,我们只需 ...

  4. ansible笔记(8):常用模块之系统类模块(二)

    ansible笔记():常用模块之系统类模块(二) user模块 user模块可以帮助我们管理远程主机上的用户,比如创建用户.修改用户.删除用户.为用户创建密钥对等操作. 此处我们介绍一些user模块 ...

  5. python【第五篇】常用模块学习

    一.主要内容 模块介绍 time &datetime模块 random os sys shutil json & pickle shelve xml处理 yaml处理 configpa ...

  6. Python函数篇(6)-常用模块及简单的案列

    1.模块   函数的优点之一,就是可以使用函数将代码块与主程序分离,通过给函数指定一个描述性的名称,并将函数存储在被称为模块的独立文件中,再将模块导入主程序中,通过import语句允许在当前运行的程序 ...

  7. ansible笔记(7):常用模块之系统类模块

    ansible笔记():常用模块之系统类模块 cron模块 cron模块可以帮助我们管理远程主机中的计划任务,功能相当于crontab命令. 在了解cron模块的参数之前,先写出一些计划任务的示例,示 ...

  8. ansible笔记(9):常用模块之包管理模块

    ansible笔记():常用模块之包管理模块 yum_repository模块 yum_repository模块可以帮助我们管理远程主机上的yum仓库. 此处我们介绍一些yum_repository模 ...

  9. ansible笔记(6):常用模块之命令类模块

    ansible笔记():常用模块之命令类模块 command模块 command模块可以帮助我们在远程主机上执行命令 注意:使用command模块在远程主机中执行命令时,不会经过远程主机的shell处 ...

随机推荐

  1. 修改admin中App的名称与表的名称

    修改APP的名称: # coding:utf-8 from django.apps import AppConfig import os default_app_config = 'repositor ...

  2. React中配置Sass引入.scss文件无效

    React中配置Sass引入.scss文件无效 在react中使用sass时,引入.scss文件失效尝试很多方法没法解决,最终找到解决方法,希望能帮助正在坑里挣扎的筒子~ 在node_modules文 ...

  3. C# List<Object>值拷贝

    using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Run ...

  4. python基础操作---string

    #coding:utf-8 var1 = 'Hello World!' print var1[::] print len(var1) print var1[0:len(var1)] print var ...

  5. PAT Advanced 1011 World Cup Betting (20 分)

    With the 2010 FIFA World Cup running, football fans the world over were becoming increasingly excite ...

  6. hdu 1506 单调栈

    #include <bits/stdc++.h> #define PI acos(-1.0) #define mem(a,b) memset((a),b,sizeof(a)) #defin ...

  7. update_all_fun(send recv)

    '''Send messages through all edges >>> update all nodes.DGLGraph.update_all(message_func='d ...

  8. Eclipse开发工具的编码问题

    乱码:文件有一个编码,打开文件的工具(Eclipse或者浏览器)有一个编码,当两个编码不同就会出现编码异常或乱码. 参考: Eclipse修改编码格式 背景:在Eclipse的开发使用中,我们经常使用 ...

  9. PHP程序员要看的书单

    想提升自己,还得多看书!多看书!多看书! 下面是我收集到的一些PHP程序员应该看得书单及在线教程,自己也没有全部看完.共勉吧! Github地址:https://github.com/52fhy/ph ...

  10. Spring Boot 使用Mybatis注解开发增删改查

    使用逆向工程是遇到的错误 错误描述 org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): c ...