python常用模块

1. time与datetime模块

1.1 time模块

1.1.1 时间的三种形式

  • 时间戳
    print(time.time())
  • 格式化时间字符串
print(time.strftime("%Y-%m-%d %X"))
#2018-08-19 15:48:25
  • 结构化时间

结构化的时间(struct_time):struct_time元组共有9个元素共九个元素:(年,月,日,时,分,秒,一年中第几周,一年中第几天,夏令时)

t=time.localtime()
得到时间对象t,可以取出元组中具体的信息

print(time.localtime()) 本地时区
# time.struct_time(tm_year=2018, tm_mon=8, tm_mday=19, tm_hour=15, tm_min=59, tm_sec=4, tm_wday=6, tm_yday=231, tm_isdst=0)

print(time.gmtime())  国际标准时区
#time.struct_time(tm_year=2018, tm_mon=8, tm_mday=19, tm_hour=7, tm_min=59, tm_sec=4, tm_wday=6, tm_yday=231, tm_isdst=0)

1.1.2 三种时间形式的转换

  • 时间戳转化为结构化时间
    print(time.localtime(23567777))
  • 结构化时间转为时间戳
    print(time.mktime(time.localtime()))
  • 结构化时间转化为格式化时间
    print(time.strftime('%Y',time.localtime()))
  • 格式化时间转为结构化时间
    print(time.strptime('2011-03-07','%Y-%d-%m'))
  • linux系统 时间格式
print(time.asctime())
print(time.ctime())
print(time.strftime('%a %b %d %H:%M:%S %Y'))
#Sun Aug 19 16:30:59 2018

用asctime和ctime将结构化时间和时间戳转化为格式化时间字符
print(time.asctime(time.localtime()))
#Sun Aug 19 16:36:17 2018
print(time.ctime(123123123))
#Mon Nov 26 08:52:03 1973

1.2 datetime模块

  • 获取当前时间
print(datetime.datetime.now())
#2018-08-19 16:43:08.649923
  • 时间戳转为格式化时间
print(datetime.datetime.fromtimestamp(1231233213))
#2009-01-06 17:13:33
  • 获取之前与未来时间
三天前与三天后时间
print(datetime.datetime.now() + datetime.timedelta(days=+3))
print(datetime.datetime.now() + datetime.timedelta(days=-3))

s=datetime.datetime.now()
print(s.replace(month=4))
随机指定年月日时分秒
  • 当天
from datetime import date
now = date.today()
print(now)

2. random模块

import random
print(random.random())  #大于0且小于1的小数
print(random.randint(1,3))  #大于等于1且小于等于3的整数
print(random.randrange(1,3)) #大于等于1且小于3的整数
print(random .choice([1,23,[4,5]]))  #1或23或[4,5]
print(random.sample([1,'23',[4,5]],2)) #列表元素任意2个组合
print(random.uniform(1,3))#大于1小于3的小数
item=[1,3,5,7,9]
random.shuffle(item) #打乱item的顺序,相当于"洗牌"
print(item)
  • 随机验证码
注:验证码包含数字、大小写字母(65~90为26个大写英文字母,97~122号为26个小写英文字母, Chr,返回以数值表达式值为编码的字符。
import random
def make_code(n):   #传入随机验证码个数
   res= ''        
   for i in range(n):
      s1= chr(random.randint(65,90))
      s2= chr(random.randint(97,122))
      s3= str(random.randint(0,9))
      res +=random.choice([s1,s2,s3])     #循环出验证码个数,返回
   return res
print(make_code(4))

3. hashlib 模块

  • 定义:hash是一种算法,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法),该算法接受传入的内容,经过运算得到一串hash值
  • 特点:
1、只要结果一样,得到的hash值必然一样
2、只要我们使用的hash算法固定,无论传入的内容有多大,得到的hash值的长度是固定的
3、不可以用hash值逆推出原来的内容
  • 用法
#1、造出hash工厂
m=hashlib.md5()
#2、运送原材料
m.update('你好啊美丽的'.encode('utf-8'))
#3、产出hash值
print(m.hexdigest()) #91c74a85807992b2f02f73cbefe7d192
  • 定义key进行加密
m=hashlib.md5('qqc'.encode('utf-8'))
m.update('你好啊美丽的'.encode('utf-8'))
print(m.hexdigest()) 
#1f61b05b7cf77f7107817df78136ffa2
  • hmac模块
import hmac
m=hmac.new('小鸡炖蘑菇'.encode('utf-8'))
m.update('hello'.encode('utf-8'))
print(m.hexdigest()) #38a608c5c394dfd4d4a882415cc1024e

4. json与pickle模块

4.1 json

  • 序列化
import json
#序列化 :内存中的数据类型转换为中间格式json
b = {'name':'qqc','age':56}
dic_b= json.dumps(b)  #转换为中间格式, json格式,单引号全都转换为双引号
with open('qqc.json','wt',encoding='utf-8')as f:
    f.write(dic_b)     #将序列化后的中间格式存入文件

简写:
with open('qqc.json','wt',encoding='utf-8')as f:
    json.dump(b,f)
  • 反序列化
 with open('qqc.json','rt',encoding='utf-8')as f:
     dic_b = f.read()      #读取序列化文件
     dic=json.loads(dic_b)   #反序列化后得到内存中的数据类型
     print(dic['name'])
     
简写:
with open('qqc.json','rt',encoding='utf-8')as f:
    dic=json.load(f)
  • 注意:
1、 dump需要一个类似于文件指针的参数(并不是真的指针,可称之为类文件对象),可以与文件操作结合,也就是说可以将dict转成str然后存入文件中;
而dumps直接给的是str,也就是将字典转成str(操作文件用dump,load,操作字符串用dumps,loads)
2、只能识别双引号,无法识别单引号
3、json存的是str,pickle 存的是bytes
4、无论数据是怎样创建的,只要满足json格式,就可以json.loads出来,不一定非要dumps的数据才能loads

5.configparser模块

  • Pyhton 标准库中用来解析配置文件(a.cfg a.ini a.cnf)
文件名:config.ini
配置文件内容:
[egon]
pwd='123'
age=18
sex='male'
salary=3.1
is_beautiful=True

[alex]
pwd='alex3714'
age=38
sex='female'
salary=2.1

解析文件方法:
import configparser
config=configparser.ConfigParser()
config.read('config.ini')  #路径 文件后缀a.cfg a.ini a.cnf...
print(config.sections())  #查看文件标题
print(config.options('egon')) #取出指定标题下的key值
print(config.items('egon')) #取出key和value,返回元组
#[('pwd', "'123'"), ('age', '18'), ('sex', "'male'"), ('salary', '3.1'), ('is_beautiful', 'True')]

#取指定标题下指定key对应的value
# res=config.get('egon','age') #用get方法返回的都是str类型
res=config.getint('egon','age')
print(res,type(res)) # 18 <class 'int'>

res=config.getfloat('egon','salary')
print(res,type(res))
res=config.getboolean('egon','is_beautiful')
print(res,type(res)) #True <class 'bool'>

6. shutil 模块

  • 作用:文件、文件夹、压缩包 处理模块

6.1拷贝文件内容

  • shutil.copyfileobj 将文件内容拷贝到另一个文件中
with open(r'F:\object\python2期\day 20\06 面向对象编程介绍.txt','rb')as f1,\
     open(r'F:\object\python2期\day 20\qc','wb') as f2:
     shutil.copyfileobj(f1,f2)
  • shutil.copyfile 通过路径拷贝文件,目标文件可以不需存在
shutil.copyfile('f1.log', 'f2.log') #目标文件无需存在
  • shutil.copy 拷贝文件和权限
    shutil.copy('f1.log', 'f2.log')

6.2 拷贝文件

  • shutil.tree 目标目录不能存在
shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))
#目标目录不能存在,注意对folder2目录父级目录要有可写权限,ignore的意思是排除(所有pyc结尾和tmp开头的除外) 
  • shutil.rmtree 递归的去删除文件
  • shutil.move 递归的去移动文件
    shutil.copytree('folder1', 'folder2) 将f1移动到f2中

6.3 压缩文件

  • 语法
 shutil.make_archive("data_bak", 'gztar', root_dir='/data')
 #(压缩过后的文件名(没有指定路径就在当前文件夹下),文件名后缀(压缩算法和打包tar组成),打包压缩的目标文件路径)
 
shutil.make_archive('jm','gztar',root_dir='F:\object\python2期\day 20\gg') 

6.4 解压文件

tar与zip压缩种类不同导入不同模块
import tarfile (import zipfile)
#打开要解压的文件
t=tarfile.open('data_bak.tar.gz','r')
#解压并指定解压后的储存路径
t.extractall('D:\SH_fullstack_s2\day20\dir')
#关闭文件
t.close()
posted @ 2018-05-29 16:23  朝朝哥  阅读(164)  评论(0编辑  收藏  举报