python常用内置模块及相关函数方法

  • time

    • time() 当前时间戳, 10位.6~7位
    • localtime() 当前(本地)时间元组
    • ctime(float_time) 将时间戳转成时间格式的字符串
    • gmtime() 获取格林的世界时间元组对象
    • mktime(time_tuple) 将元组转成时间戳
      -* strftime(format, time_tuple) 将时间元组转成字符串
      -* strptime(time_str, format) 将字符串转成时间元组
      %Y Year with century as a decimal number.
      %m Month as a decimal number [01,12].
      %d Day of the month as a decimal number [01,31].
      %H Hour (24-hour clock) as a decimal number [00,23].
      %M Minute as a decimal number [00,59].
      %S Second as a decimal number [00,61].
      %z Time zone offset from UTC.
      %a Locale’s abbreviated weekday name.
      %A Locale’s full weekday name.
      %b Locale’s abbreviated month name.
      %B Locale’s full month name.
      %c Locale’s appropriate date and time representation.
      %I Hour (12-hour clock) as a decimal number [01,12].
      %p Locale’s equivalent of either AM or PM.
    • sleep(n) 当前线程休眠n 秒
    • process_time() 返回当前CPU响应时间
  • datetime 模块

    • datetime 类

      • 初始化()方法的位置参数: year, month, day, hour, minute, second
      • now() 当前时间,返回datetime的时间元组
      • 实例方法 strftime(format)
      • 静态方法 strptime(time_str, format) 将时间的字符串按format格式转成datetime实例对象
        eg. datetime.datetime.strptime(‘9月2010年20日’, ‘%m月%Y年%d日’)
      • 两个datetime实例可以相减, 得到timedelta
        delta = datetime.datetime(2020,10,12) - datetime.datetime(2010,11,20,15,10,22)
        (delta.days//365, delta.days%365, delta.seconds//3600, delta.seconds%3600//60, delta.seconds%3600%60 )
    • timedelta 类
      datetime 和 timedelta进行计算(加 和 减)
      timedelta(days=1, seconds=100), 参数可以是 weeks, days, hours, minutes, seconds

  • sys

    • sys.exit(0) 正常退出
    • path Python运行环境时导包或执行命令的搜索路径,同Pycharm的source root标识的目录。
    • version 当前的解析器的版本信息
    • argv 读取命令行参数
    • getdefaultencoding() 获取默认的字符集
    • platform 获取当前操作系统的平台信息, 如Win10下返回 win32, Mac下返回darwin
    • modules 获取当前解析器的模块字典
  • os

    • mkdir() 创建单个目录, 如果上级目录不存在时,则抛出异常FileNotFoundError
    • makedirs() 级联创建目录,如果上级目录不存在时,则会自动创建
    • getcwd() 获取当前的目录位置
    • remove(path) 删除单个文件, 如果path是一个目录时,则抛出异常 PermissionError
    • rmdir(path) 删除单个目录
    • removedirs(path) 删除多级目录,从内(子)向外(父)删除目录
    • chdir(path) 切换目录
    • chmod(path) 修改文件权限
    • listdir(path) 列出path目录下的文件及子目录,默认为``空时,表示当前目录。
    • rename(src_path, dst_path) 修改文件名或目录名
    • path 子模块
      • join(dir, filename)
      • split(path) 分隔目录和文件
      • splitext(path) 分隔文件和扩展名
      • exists(path) 判断文件或目录是否存在
      • getsize(path) 文件大小
      • dirname(path) 获取目录名
      • abspath(filename) 获取文件名的绝对路径
      • getatime()/getctime()/getmtime() a=access, c=create, m=modify
      • basename() 文件名
      • isdir()/isfile()/islink()/ismount()
    • stat(path) 获取文件的状态信息,如时间/大小相关。
    • poen(cmd, mode=‘r’, buffering=-1) 创建子进程,执行cmd命令,返回流stream对象。
    • system(cmd) 创建子进程来执行cmd命令, 无返回值。
  • math

    • floor() 下行取整
    • ceil() 上行取整
    • sqrt() 平方根
    • pow(num, i) 次幂(方)
    • pi 圆周率
    • fabs() 绝对值
    • fmod() 取余数
    • fsum() 求和
    • modf() 整数与小数分开的元组
  • random

    • random()
    • randint()
    • uniform()
    • choice()
    • choices()
    • shuffle() 打乱列表的顺序
    • sample(population, k) 从population中随机获取k个可重复的元素
  • re

    • compile() 创建一个正则对象
    • match() 匹配
    • search() 搜索第一个匹配的结果
    • findall() 查找所有匹配的结果
    • sub(正则,replace_str, str, count=0) 匹配正则的字符串,并替换指定的内容
  • copy

  • copy.copy() 浅拷贝

  • copy.deepcopy() 深拷贝

  • json
    将python的dict或list转成json格式的字符串:序列化

    • json.dumps(dict|list, skipkeys=False, ensure_ascii=True)
    • json.dump(dic|list, file, …)

    将json格式的字符串转成python的dict或list对象:反序列化

    • json.loads(str)
    • json.load(str, file)
  • logging

    • getLogger(name)
    • info()
    • debug()
    • warning()
    • error()
    • critical()/fatal()
    • basicConfig(format, datefmt, filename, filemode, level, handlers) 配置root记录器
    • StreamHandler类
    • FileHandler类
    • handlers
      • SMTPHandler
      • HTTPHandler
      • TimeRotatingFileHandler
    • filters
      • Filter类
  • hashlib

    • md5
    • sha1
    • sha256
  • base64

    • b64encode()
    • b64decode()
    • b32encode()
    • b32decode()
  • csv

    • reader(file, dialect=‘excel’) 可迭代的
    • writer(file, dialect=“excel”) 写入器
      • writerow() 单行, 元组
      • writerows() 多行, 多个元组
    • DictReader 可迭代的
    • DictWriter
      • writeheader()
      • writerow()
      • writerows()
  • pickle

    • pickle.dumps(obj) 将python的任意对象序列化为字节数据

    • pickle.dump(obj, file) 将对象序列化的字节数据写入到文件中

    • pickle.load(file)

    • pickle.loads(bytes)

  • collections

    • namedtuple()
    • DefaultDict()
    • Counter
    • Deque 双向队列
    • OrderedDict 有序字典, 添加的key是有序的
      • move_to_end(key, last=False) last=True移动最后,last=False移动最前
  • functools

    • partial(fun, *args, **keywords) 对函数进行局部控制,固定个别的目标函数的参数

    • reduce(function, iteratable) 递归计算

    • update_wrapper(装饰器函数, 目标函数) 返回可更新目标函数的包装函数
      装饰函数: runtime
      目标函数: save
      产生闭包: s = update_wrapper(runtine, save)
      更新目标函数并调用闭包函数: s(save)(‘tb_user’, 1, ‘disen’)

      def runtime(fun):
      … def wrapper(*args, **kwargs):
      … print(’–runtime wrapper—’)
      … return fun(*args, **kwargs)
      … return wrapper

      def save(table, id, name):
      print(table, id, name)

  • itertools

    • itertools.count(start, step) 无限循环的计数器(内部是一个生成器, 可以使用next© 获取)
      c = count(1, 1)
      next©

    • cycle(iterable) 循环读取的生成器, 可以使用next()获取

    • repeat(obj, times) 可重复迭代next()的times次数的obj对象

    • permutations(iterable, width) 生成iterable中每个元素的组合的生成器,长度为width。

    • chain(*iterables)

    • groupby(iterable) 去除相邻的元素

  • urllib

    • urllib.request

      • urlopen(url, data, headers)
      • urretrieve(url, filename)
      • build_opener(*handlers)
      • HTTPHandler
      • HTTPCookieProcessor
      • ProxyHandler(proxies={})
    • urllib.parse

      • quote
      • unquote
      • urlencode({}, encoding)
  • string

  • digits

  • ascii_letters

  • ascii_lowercase

  • ascii_upercase

  • threading

    • Thread(target=, args=, name=)
    • current_thread()
    • Lock
    • local() 本地变量对象
    • Condition(Lock) 线程的条件变量
      • acquire()
      • release()
      • wait()
      • notify()
      • notify_all()
      • notifyAll()
  • multiprocessing

    • Process(target, name, args)
    • current_process() 当前进程
    • Lock进程锁
    • Queue 队列
    • Manager 共享内存
      • Array
      • Value ???
    • Pipe(duplex=True)
  • queue

    • Queue(max_size=0)
  • asyncio

    • coroutine
    • get_event_loop()
    • wait()
    • sleep
  • http.client

    • HTTPRequest
    • HTTPResponse
  • socket

    • socket(socket.AF_INET|AF_UNIX)
    • socket.bind((host, port) | ‘/var/run/x.sock’) 服务进程(服务器)绑定
    • socket.listen() 服务器(进程)开始监听
    • client, address = socket.accept() 服务器等待客户端(进程)连接
    • socket.recv(buffer) 接收消息, 消息的数据是字节
    • socket.send(b’’) 发送消息
    • socket.connect((host, port) | ‘/var/run/x.sock’) 客户端连接指定服务器或进程
    • socket.close() 关闭连接
    • socket.sendall(b’’) 一次发送消息
    • socket.sendfile() 发送文件
    • socket.settimeout(timeout) 设置超时时间
  • abc

    • ABC类
    • abstractclassmethod 装饰器函数 , 类方法
    • abstractmethod 装饰器函数, 实例方法
    • abstractstatimethod 静态方法

你可能感兴趣的:(python)