ningleesherry 发表于 2018-8-9 11:18:36

python_day5_模块

  5.1 模块说明
  5.2 模块
time  datetime
  random
  os
  shutil
  json
  pickle
  shelve
  xml
  hashlib
  hmac
  正则表达式
  configparser
  模块定义:
  模块:从逻辑上来组织python代码(定义变量,函数,类,逻辑,其就是为了实现一个功能),本质就是.py结尾的python文件
  包: 用来从逻辑上组织模块,与文件的区别就是带了一个__init__.py文件
  模块导入:导入模板就是把Python文件解释了一遍
  import module_name                           #导入单个模块
  import module_name1,module_name2,module_#**    #导入多个模块
  调用方法module_name.方法
  from module_file import *                      #导入模块中的所有方法及函数 (不建议使用)
  from module_file import module_name            #导入模块中的方法或函数   (也可以多个方法)
  from module_file import module_name as alias   #定义module_name别名
  包导入:    导入包就是解释__init__文件
    import py_pack_name   # 执行包下面的 __init__.py文件  
    from module_name_packerimport module_name
  模块分类:
  1、标准库
  2、开源模块(第三方模块)
  3、自定义
  #time 模块
      time.sleep()         # (秒)  
      print(time.time())   # 时间戳 1506492926.3223119    从1970年1月1日开始记秒
  
      print(time.localtime())
  
          # time.struct_time(tm_year=2017, tm_mon=9, tm_mday=27, tm_hour=14, tm_min=11, tm_sec=46, tm_wday=2, tm_yday=270, tm_isdst=0)
  

  
      time.strftime()      # now_time=time.localtime()
  
                           # print(time.strftime("%Y-%m-%d %H:%M:%S",now_time))
  
                           # 结果: 2017-09-27 14:04:27
  ti=time.strptime('2017-09-27 14:15:26','%Y-%m-%d %H:%M:%S')   # 格式化字符串打印的结果与time.time一样,但有值之后就能直接取出年月日值
  print(ti.tm_hour)   # 14   这样能直接打印出月份
  # 将时间戳转换成时间
      x=time.localtime(time.time())  
      print(time.strftime('%Y-%m-%d %X',x))
  # 将当前时候转换为时间戳
      print(time.mktime(time.localtime()))  # datetime 模块
      import datetime  
      print(datetime.datetime.now())      # 获取当前时间 2017-11-02 14:39:44.929088
  
      print(datetime.datetime.now()+datetime.timedelta(3))          # 往前加3天
  
      print(datetime.datetime.now()+datetime.timedelta(hours=-3))   # 3小时以前的时间
  # random随机数 限定0-1
      print(random.random())   #随机获取一个0-1之间的随机数  
      print(random.randint(1,3))# 从1-3随机挑选一个数
  
      print(random.randrange(1,100))# 随机生成一个范围内的数值
  
      print(random.sample(['123','32','3'],2))    # 列表随机生成一个2位的数['32', '123']
  
      print(random.choice(['1','2','3']))         # 随机生成一个数值
  # chr转换ascii码对应的数值表 如65对应A      65-91表示ASCII码的 A-Z
  常见字符的ASCII码值如下:空格的ASCII码值为32;数字0到9的ASCII码值分别为48到57;大写字母“A”到“Z”的ASCII码值分别为65到90;小写字母“a”到“z”的ASCII码值分别为97到到122。
  # 生成一个6位的随机生成数
      import random  

  
      def v_random():
  
            a_num=''
  
            for i in range(6):
  
                r_num=random.choice()
  
                a_num+=str(r_num)
  
            print(a_num)
  

  
      v_random()            # 打印结果 cyY4N6
  # os 模块
      os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径  
      os.chdir("dirname")改变当前脚本工作目录;相当于shell下cd
  
      os.curdir返回当前目录: ('.')
  
      os.pardir获取当前目录的父目录字符串名:('..')
  
      os.makedirs('dirname1/dirname2')    可生成多层递归目录
  
      os.removedirs('dirname1')    若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
  
      os.mkdir('dirname')    生成单级目录;相当于shell中mkdir dirname
  
      os.rmdir('dirname')    删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
  
      os.listdir('dirname')    列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
  
      os.remove()删除一个文件
  
      os.rename("oldname","newname")重命名文件/目录
  
      os.stat('path/filename')获取文件/目录信息
  
      os.name    输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
  
      os.environ获取系统环境变量
  
      os.path.isabs(path)如果path是绝对路径,返回True
  
      os.path.isfile(path)如果path是一个存在的文件,返回True。否则返回False
  
      os.path.isdir(path)如果path是一个存在的目录,则返回True。否则返回False
  
      os.path.join(path1[, path2[, ...]])将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
  
      os.path.getatime(path)返回path所指向的文件或者目录的最后存取时间
  
      os.path.getmtime(path)返回path所指向的文件或者目录的最后修改时间
  # 重要的方法
            os.sep    输出操作系统特定的路径分隔符,win下为"\\",Linux下为"/"  
            os.linesep    输出当前平台使用的行终止符,win下为"\t\n",Linux下为"\n"
  
            os.pathsep    输出用于分割文件路径的字符串
  
            os.system("bash command")运行shell命令,直接显示
  
            os.path.abspath(path)返回path规范化的绝对路径
  
            os.path.split(path)将path分割成目录和文件名二元组返回
  
            os.path.exists(path)如果path存在,返回True;如果path不存在,返回False
  
            os.path.dirname(path)返回path的目录。其实就是os.path.split(path)的第一个元素
  
            os.path.basename(path)返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
  # 跨平台需要   windows的是\ linux的是/
                s=os.sep  
                os.chdir(r'C:%sUsers\xiong\Desktop\untitled'%s)
  
                print(os.getcwd())
  # shutil
            shutil.copyfileobj(file_src,file_dst)  
                file1= open('file_name.txt',encoding='utf-8')
  
                file2= open('file_name.txt','w',encoding='utf-8')
  
                shutil.copyfileobj(file1,file2)
  

  
            shutil.copymode(src,dst)         #仅拷贝权限。内容,组,用户不变
  
            shutil.copystat(源文件,目标文件)   # 拷贝文件,以及状态信息
  
            shutil.copy(源文件,目标文件)       # 拷贝文件及权限
  
            shutil.copy2(源文件,目标文件)      # 拷贝文件及状态信息
  
            shutil.copytree(源目录,目标目录)   # 拷贝整个目录
  
            shutil.rmtree(目录名称)            # 删除整个目录(有风险)
  
            shutil.mak_archive(base_name,format,...)    # 创建压缩包并返回文件路径
  
            shutil.make_archive(r'C:\xx\day1','zip',r'C:\xx\day1')      #压缩day1目录,并保存在xx目录下 类型是zip
  base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
  format: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”
  root_dir:   要压缩的文件夹路径(默认当前目录)
  owner:用户,默认当前用户
  group:组,默认当前组
  logger: 用于记录日志,通常是logging.Logger对象
  # json 序列化      只能处理简单的字典文件
      json.dumps()      序列化字典  
            import json
  
            info = {
  
                "name":"xiong",
  
                "age": 50,
  
                "sex": 'man'
  
            }
  
            with open('json_test.txt','w',encoding='utf-8') as file:
  
                file.write(json.dumps(info))      # 用法一
  
                # json.dump(info,file)            # 用法二
  

  

  
      json.loads()      反序列化字典      只能dump一次字典,
  
            with open('json_test.txt','r',encoding='utf-8') as file:
  
                # data=json.loads(file.read())      # 用法一
  
                data=json.load(file)                # 用法二
  
                print(data)
  pickle 序列化字典    可处理复制的字典,但只能在py上运行,其它语言不行
      pickle.dumps()      序列化字典   相等于 pickle.dump(对象,文件)  
      import pickle
  
      def du(hobby):
  
            print("hobby",hobby)
  
      info = {
  
            "name":"xiong",
  
            "age": 50,
  
            "hobby": du
  
      }
  
      with open('json_test.txt','wb') as file:
  
            file.write(pickle.dumps(info))
  

  
      pickle.loads()      反序列化字典相等于 pickle.load(文件)
  
      import pickle
  

  
      def du(hobby):
  
            print("hobby",hobby)
  # 以二进制的方式查看,函数必须在反序列号中也存在,否则将会报错
  with open('json_test.txt','rb') as file:
  # 打开文件并以行的文件阅读
  data=pickle.loads(file.read())
  # 传递参数给函数,pickle 函数序列化中能在py中能使用,其它语言没法用
  print(data['hobby']('cat'))
  # shelve 模块 一个简单的k,v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持的Py数据格式
    import shelve,datetime  

  w=shelve.open('shelve.txt')   # 先打开一个文件
  info={'age':222,'jobs':'it'}
  name=['xiong','ab']
  w["info"]=info      # 持久化数据
  w["name"]=name
  w['date']=datetime.datetime.now()
  

  w.close()         #关闭文件
  

  # 查看shelve序列化的数据
  w=shelve.open('shelve.txt')
  print(w.get("name"))
  print(w.get("info"))
  w.close()
  

  打印结果['xiong', 'ab']
  {'age': 222, 'jobs': 'it'}
  2017-11-02 21:17:43.986210
  # xml模块
import xml.etree.ElementTree as ET  

  tree=ET.parse('xmltests.xml')# 打开xml文件
  root=tree.getroot()# 获取xml文件树
  print(root.tag)# 打印标签首页
  

  for chi in root:# 循环标签首页
  print(chi.tag,chi.attrib)# 打印标签中所有的标签以及属性
  for i in chi:
  print(i.tag,i.text,i.attrib)# 打印内容标签,内容,以及属性资料
  # 只打印xml中树中某一个键值对的信息
for i in root.iter('gdppc'):  
            print(i.tag,i.text)
  

  

  import hashlib
  

  m=hashlib.md5()
  print(m)
  

  m.update('hello'.encode('utf8'))
  print(m.hexdigest())
  configparser模块
  # 给配置文件中写入内容
import configparser  conf=configparser.ConfigParser()# 文件操作句柄
  conf['DEFAULT']={'one1':'1',
  'two2':'2'}
  conf['DEFAULT']['three3']='3'
  with open('conf.tini','w',encoding='utf-8') as confile:
  conf.write(confile)
  configparser模块_查看
  # 打印文件的全部内容,以元组的形式
with open('conf.tini','r',encoding='utf-8') as xx:  for i in xx:
  print(i.split())
  # 读配置文件中的sections, DEFAULT无法打印出来, 需要其它选项
  conf.read('conf.ini')
  print(conf.sections())
  # 打印结果 ['test2']
  # 打印DEFAULT键值对的值
  print(conf.defaults())
  # 打印结果 OrderedDict([('one1', '1'), ('two2', '2'), ('three3', '3')])# OrderedDict有序的排序
  # 判断键是否存在配置文件中
  print('test2' in conf)
  # 结果: True
  print('test3' in conf)
  # 结果: False
  # 取出配置文件中键值
  print(conf['test2']['test'])
  # 结果: test1
  # 打印某个键
  for i in conf['test2']:
  print(i)
  # 打印结果:打印这个键的时候 它也会打印出DEFAULT的特殊值
  test
  test2
  one1
  two2
  three3
  # 删除配置文件中的键值
conf=configparser.ConfigParser()# 定义一个操作句柄,没有这个配置操作会出错  conf.read('conf.tini')      # 每次操作的时候一定要先打开文件然后再操作
  conf.remove_section('test2')# 删除键
  conf.write(open('conf.tini','w'))# 修改删除键的配置文件,此处需要注意的是这里是覆盖原文件
  # 只是修改覆盖而不是直接删除
      conf.remove_option('test3','ess')   选项 键,值  #   键   值    内容
      conf['test3']['ess']='333'          # 新加一个键  
      conf.set('test3','ess','4444')      # 删除新加的键
  # 删除配置的选项
      conf.remove_option('xxxxx','xx3')  
      conf.write(open('confi.txt','w',encoding='utf-8'))
  # 注意要修改或删除某个值时,一定要带有 操作句柄以及修改文件的目录
      conf=configparser.ConfigParser()  
      conf.write(open('conf.tini','w'))
  # hashlib 模块
      import hashlib  

  
      m2=hashlib.md5()      # md5加密
  
      m2.update(b'A97yd2')    # 设置一个md5加密密码
  
      print(m2.hexdigest())   # 打印16进制的数值出来
  # hmac 模块中文字符需要encode
      h = hmac.new(b'teststs')  
      print(h.hexdigest())
  正则表达式
  re(正则表达式) 是py引入的一个接口
  元字符
b 表示一次或零次  .:匹配任意单个字符
  [] 中括号                : 匹配指定范围内的任意单个字符,取消元字符的特殊功能()
  [^字符] 意味着取反   []中所有的非
  [^]中括号加尖括号: 匹配指定范围之外的任意单个字符    逻辑非
  匹配字符次数:(贪婪模式.*尽可能长的匹配)
  () 一个组内容
  | 或a|b    a或者b
  *:匹配其前面的字符 0到无穷次
  +: 至少匹配1次到无穷次
  ?: 可以匹配 0次或1次惰性匹配
  .* : 任意长度的任意字符
  {m,n}:匹配其前面的字符至少m次,至多N次
  {0,} 等于无穷次
  {0,1} 等于?
  {6}至少六次      {1,3}最多三次
  位置锚定:
^:锚定行首,此字符后面的匹配到的任意内容必须出现在行首  $   :锚定行尾,此字符后面的匹配到的任意内容必须出现在行尾
  

  []字符集:表示只要有其中一个就能获取
  

  \ 反斜杠后边跟元字符去除特殊功能
  反斜杠后边跟普通字符实现特殊功能
  

  \d匹配任何十进制数;它相当于类 。
  \D 匹配任何非数字字符;它相当于类 [^0-9]。
  \s匹配任何空白字符;它相当于类 [ \t\n\r\f\v]。
  \S 匹配任匹配任何字母数字字符;它相当于类何非空白字符;它相当于类 [^ \t\n\r\f\v]。
  \w。
  \W 匹配任何非字母数字字符;它相当于类 [^a-zA-Z0-9_]
  \b匹配一个特殊字符边界,比如空格 ,&,#等
  ?P<id> 固定格式起一个名字
  ret=re.search(r'(?P<www>{3})\.(?P<domain>\w*)','www.baidu.com')
  print(ret.group('www'))
  print(ret.group('domain'))
  打印结果: www
  baidu
  匹配出满足条件的第一个结果
xx.search('xx','sdfasdffdsxx').group()    # 不加.group打印出来的是一个对象  方法
#查找findall(pattern, string, flags=0)  1、findall(): 所有结果都返回到一个列表中
  # 使用: findall(匹配规则,内容)
  2、search() : 返回一个对象(object), 对象可以调用group() 方法来获取返回结果
  3、match() :只在字符串开始匹配 跟 ^锚定类式
  4、split() : 分割换行
  5、sub() :sub('规则','替换的新内容','替换内容')
  re.sub('x..x','ax','xyyx')
  打印结果: ax
  

  6、compile() : 将规则预先定义好, 然后再使用
  

  # findall会先打印出组内的内容,
  print(re.findall('www\.(163|222)\.com' , &quot;www.163.com&quot;))# 打印结果: ['163']
  # 取消优先打印组内的内容,将结果全部打印出来
  print(re.findall('www\.(?:163|222)\.com' , &quot;www.163.com&quot;))
  # 打印结果: ['www.163.com']
  configparser模块
  # 给配置文件中写入内容
import configparser  conf=configparser.ConfigParser()# 文件操作句柄
  conf['DEFAULT']={'one1':'1',
  'two2':'2'}
  conf['DEFAULT']['three3']='3'
  with open('conf.tini','w',encoding='utf-8') as confile:
  conf.write(confile)
  configparser模块_查看
# 打印文件的全部内容,以元组的形式  with open('conf.tini','r',encoding='utf-8') as xx:
  for i in xx:
  print(i.split())
  

  # 读配置文件中的sections, DEFAULT无法打印出来, 需要其它选项
  conf.read('conf.ini',encoding='utf-8')
  print(conf.sections())
  # 打印结果 ['test2']
  

  # 打印DEFAULT键值对的值
  print(conf.defaults())
  # 打印结果 OrderedDict([('one1', '1'), ('two2', '2'), ('three3', '3')])# OrderedDict有序的排序
  

  # 判断键是否存在配置文件中
  print('test2' in conf)
  # 结果: True
  print('test3' in conf)
  # 结果: False
  

  # 以列表打印出该配置段中所有的选项
  print(conf.items('test2'))
  # 结果: [('name', 'xx'), ('age', 'man'), ('human', 'y')]
  

  # 取出配置文件中键值
  print(conf['test2']['test'])
  # 结果: test1
  

  # 打印某个键
  for i in conf['test2']:
  print(i)
  # 打印结果:打印这个键的时候 它也会打印出DEFAULT的特殊值
  test
  test2
  one1
  two2
  three3
  添加
# 添加一个配置段  conf=configparser.ConfigParser()# 创建一个对象
  conf.add_section('test')# 添加配置段
  conf.set('test','name','xiong')# 添加配置段文件
  conf.write(open('i.ini','w'))# 修改并添加文件
  

  修改
  # 删除配置文件中的键值
  conf=configparser.ConfigParser()# 定义一个操作句柄,没有这个配置操作会出错
  conf.read('conf.tini')      # 每次操作的时候一定要先打开文件然后再操作
  conf.remove_section('test2')# 删除整个标题
  conf.write(open('conf.tini','w'))# 修改删除键的配置文件,此处需要注意的是这里是覆盖原文件
  

  # 只是修改覆盖而不是直接删除
  conf.remove_option('test3','ess')   选项 键,值
  #   键值    内容
  conf['test3']['ess']='333'# 新加一个键
  conf.set('test3','ess','4444')# 删除新加的键
  # 注意要修改或删除某个值时,一定要带有 操作句柄以及修改文件的目录
conf=configparser.ConfigParser()  conf.write(open('conf.tini','w'))
页: [1]
查看完整版本: python_day5_模块