21天学python之3高级语法:模块

模块
用一堆代码实现了某个功能的集合,分为内置模块、自定义模块、开源模块

导入模块
import module
from module.xx.yy import yy
from module.xx.yy import yy as rename
from module.xx.yy import *

导入一个包,解释器解释该包下的__init__.py文件
模块的安装pip install module


常用的6个内置模块
1、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.sep    输出操作系统特定的路径分隔符,win下为"\",Linux下为"/"
os.linesep    输出当前平台使用的行终止符,win下为"	
",Linux下为"
"
os.pathsep    输出用于分割文件路径的字符串
os.name    输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
os.system("bash command")  运行shell命令,直接显示
os.environ  获取系统环境变量
os.path.abspath(path)  返回path规范化的绝对路径
os.path.split(path)  将path分割成目录和文件名二元组返回
os.path.dirname(path)  返回path的目录。其实就是os.path.split(path)的第一个元素
os.path.basename(path)  返回path最后的文件名。如何path以/或结尾,那么就会返回空值。即os.path.split(path)的第二个元素
os.path.exists(path)  如果path存在,返回True;如果path不存在,返回False
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所指向的文件或者目录的最后修改时间

  

2、random

#生成4位随机验证码
import random
checkcode = ''
for i in range(4):
    current = random.randrange(0,4)
    if current != i:
        temp = chr(random.randint(65,90)) #随机的大写字母
    else:
        temp = random.randint(0,9)
    checkcode += str(temp)
print(checkcode)

随机数,

random.random()  #在[0,1)范围内

random.randint(1,2) # [1,2]的随机整数

random.randrange(1,10) #[1,10]的随机整数

3、loging 记录日志

import logging
 
 
logging.basicConfig(filename='log.log',
                    format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S %p',
                    level=10)
 
logging.debug('debug')
logging.info('info')
logging.warning('warning')
logging.error('error')
logging.critical('critical')
logging.log(10,'log')

  记录日志,只有大于当前日志等级的操作才会被记录,debug<info<warning<error<critical

4、time&datetime

     时间相关的操作,时间有三种表示方式:

  • 时间戳               1970年1月1日之后的秒,即:time.time()
  • 格式化的字符串    2014-11-11 11:11,    即:time.strftime('%Y-%m-%d')
  • 结构化时间          元组包含了:年、日、星期等... time.struct_time    即:time.localtime()
  •  time.time()
     time.mktime(time.localtime())
      
     time.gmtime()    #可加时间戳参数
     time.localtime() #可加时间戳参数
     time.strptime('2014-11-11', '%Y-%m-%d')
      
     time.strftime('%Y-%m-%d') #默认当前时间
     time.strftime('%Y-%m-%d',time.localtime()) #默认当前时间
     time.asctime()
     time.asctime(time.localtime())
     time.ctime(time.time())
    

      datetime 参考 https://www.liaoxuefeng.com/wiki/1016959663602400/1017648783851616

5、re

re模块用于对python的正则表达式的操作。

字符:

  . 匹配除换行符以外的任意字符
  w 匹配字母或数字或下划线或汉字
  s 匹配任意的空白符
  d 匹配数字
   匹配单词的开始或结束
  ^ 匹配字符串的开始
  $ 匹配字符串的结束

次数:

  * 重复零次或更多次
  + 重复一次或更多次
  ? 重复零次或一次
  {n} 重复n次
  {n,} 重复n次或更多次
  {n,m} 重复n到m次

IP:
^(25[0-5]|2[0-4]d|[0-1]?d?d)(.(25[0-5]|2[0-4]d|[0-1]?d?d)){3}$
手机号:
^1[3|4|5|8][0-9]d{8}$

 

1、match(pattern, string, flags=0)

从起始位置开始根据模型去字符串中匹配指定内容,匹配单个

2、search(pattern, string, flags=0)

根据模型去字符串中匹配指定内容,匹配单个
3、group和groups
4、findall(pattern, string, flags=0)

上述两中方式均用于匹配单值,即:只能匹配字符串中的一个,如果想要匹配到字符串中所有符合条件的元素,则需要使用 findall。
5、sub(pattern, repl, string, count=0, flags=0)

用于替换匹配的字符串
6、split(pattern, string, maxsplit=0, flags=0)
根据指定匹配进行分组

 参考 https://www.cnblogs.com/wupeiqi/articles/4963027.html 

6、hashlib 加密算法

import hashlib

md5 = hashlib.md5()
md5.update('how to use md5 in '.encode('utf-8'))
md5.update('python hashlib?'.encode('utf-8'))
print(md5.hexdigest())

  

原文地址:https://www.cnblogs.com/yt1234/p/14950768.html