python-笔记(六)模块操作以及常用模块简介

模块、包

什么是模块?
模块实质上就是一个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:pythonScripts ,发现文件夹下游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:yzcod")) 更改当期那目录
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:yzzuoyeduguanglong_libday06>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())

未完待续......

原文地址:https://www.cnblogs.com/lingxia/p/7505272.html