(6)python内置函数,python常用模块

官方文档:https://docs.python.org/zh-cn/3.8/library/index.html

【0】模块的分类

  【0.1】标准模块:比如 os,sys,time 等,这些是安装python时已经自带在python中的;

  【0.2】开源模块:比如 gitlab 上别人写好的模块,我们直接导入引用过来,就可以直接拿来用

  【0.3】自定义模块:其实就是自己写包,写Python文件,然后自己引用

【1】内置函数

官网文档:https://docs.python.org/zh-cn/3.8/library/functions.html#abs

Python 解释器内置了很多函数和类型,您可以在任何时候使用它们。以下按字母表顺序列出它们。

  

内置函数

  

abs()

delattr()

hash()

memoryview()

set()

all()

dict()

help()

min()

setattr()

any()

dir()

hex()

next()

slice()

ascii()

divmod()

id()

object()

sorted()

bin()

enumerate()

input()

oct()

staticmethod()

bool()

eval()

int()

open()

str()

breakpoint()

exec()

isinstance()

ord()

sum()

bytearray()

filter()

issubclass()

pow()

super()

bytes()

float()

iter()

print()

tuple()

callable()

format()

len()

property()

type()

chr()

frozenset()

list()

range()

vars()

classmethod()

getattr()

locals()

repr()

zip()

compile()

globals()

map()

reversed()

__import__()

complex()

hasattr()

max()

round()

 

【2】time 与 datetime

【2.1】time 模块

# 3类时间格式

(1)时间戳(秒):数字时间戳格式,其实就是秒的格式

(2)时间元组(struct):time.struct_time(tm_year=2020, tm_mon=11, tm_mday=20, tm_hour=17, tm_min=12, tm_sec=44, tm_wday=4, tm_yday=325, tm_isdst=0)

(3)时间的格式化字符串:

互相转换:

   

实际演示:

(1)

import time
time.timezone      # 获取当前时区的秒,比如是 - 28800 则 28800/3600= 8 小时
time.time()        # 当前时间 - 1970.01.01(操作系统诞生时间)  时间戳秒
time.localtime()   # 本地时区的时间戳转换为字符串格式(可以传数字时间戳参数)

time.gmtime()      # UTC 标准时间的时间戳转换为字符串格式:慢了 8 小时,因为我们中国是东八区(可以传数字时间戳参数)
time.gmtime(time.time()-800000)   # UTC 标准时间的时间戳 转换为格式化字符串日期(当前时间)
a = time.localtime().tm_year  # 获取时间元组的具体值

# 元组转换
  # 元组 转成 字符串
    time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())  # '2020-11-20 17:39:57'
  # 元组转换成 默认的字符串
    time.asctime()  # 传参为元组时间,默认为对应格式的当前时间:'Fri Nov 20 17:52:59 2020'
  # 元组转换回时间戳
    time.mktime(time.localtime())  
# 字符串转换   # 字符串 转为 元组     time.strptime("2020-11-20 17:39:57","%Y-%m-%d %H:%M:%S") # time.struct_time(tm_year=2020, tm_mon=11, tm_mday=20, tm_hour=17, tm_min=39, tm_sec=57, tm_wday=4, tm_yday=325, tm_isdst=-1) # 时间戳转换   # 时间戳 转换 默认的字符串     time.ctime() # 传参为时间戳秒时间,默认为对应格式的当前时间:'Fri Nov 20 17:52:59 2020'     time.gmtime() # UTC 标准时间的时间戳转换为字符串格式:慢了 8 小时,因为我们中国是东八区(可以传数字时间戳参数)    #时间戳 转换 元组     time.localtime() # 本地时区的时间戳转换为字符串格式(可以传数字时间戳参数)

(2)

#_*_coding:utf-8_*_

import time

# print(time.clock()) #返回处理器时间,3.3开始已废弃 , 改成了time.process_time()测量处理器运算时间,不包括sleep时间,不稳定,mac上测不出来
# print(time.altzone)  #返回与utc时间的时间差,以秒计算
# print(time.asctime()) #返回时间格式"Fri Aug 19 11:14:16 2016",
# print(time.localtime()) #返回本地时间 的struct time对象格式
# print(time.gmtime(time.time()-800000)) #返回utc时间的struc时间对象格式

# print(time.asctime(time.localtime())) #返回时间格式"Fri Aug 19 11:14:16 2016",
# print(time.ctime()) #返回Fri Aug 19 12:38:29 2016 格式, 同上



# 日期字符串 转成  时间戳
# string_2_struct = time.strptime("2016/05/22","%Y/%m/%d") #将 日期字符串 转成 struct时间对象格式
# print(string_2_struct)
# #
# struct_2_stamp = time.mktime(string_2_struct) #将struct时间对象转成时间戳
# print(struct_2_stamp)


#将时间戳转为字符串格式
# print(time.gmtime(time.time()-86640)) #将utc时间戳转换成struct_time格式
# print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将utc struct_time格式转成指定的字符串格式

【2.2】datetime

#时间加减
import datetime

# print(datetime.datetime.now()) #返回 2016-08-19 12:47:03.941925
#print(datetime.date.fromtimestamp(time.time()) )  # 时间戳直接转成日期格式 2016-08-19
# print(datetime.datetime.now() )
# print(datetime.datetime.now() + datetime.timedelta(3)) #当前时间+3天
# print(datetime.datetime.now() + datetime.timedelta(-3)) #当前时间-3天
# print(datetime.datetime.now() + datetime.timedelta(hours=3)) #当前时间+3小时
# print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #当前时间+30分

# c_time  = datetime.datetime.now()
# print(c_time.replace(minute=3,hour=2)) #时间替换

【3】random 

import random
print(random.random())        # 随机浮点数:0-1的浮点数
print(random.uniform(1,10))   # 随检浮点数:指定范围的随机浮点数
print(random.randint(1,3))    # 随机整数:1-3
print(random.randrange(1,3))  # 随机整数:1-2
print(random.choice('hello'))     # 随机选择 数据类型中的一个元素
print(random.choice([10,11,12]))  # 随机选择 数据类型中的一个元素
print(random.sample('abcde',2))        # 随机选择 数据类型中的指定个数元素
print(random.sample([14,15,16,18],2))  # 随机选择 数据类型中的指定个数元素

a = [x for x in range(1,10)]
print('random.shuffle(a) 之前:',a)     # 打乱对象顺序,洗牌功能
random.shuffle(a)
print('random.shuffle(a) 之后:',a)

获取验证码实践:

import random
checkcode = ''
for i in range(4):
    current = random.randrange(0,4)  # 4位验证码,如果随机值与当前获取值相同,则该为验证码为 小写字母,否则为0-9的数字
    if current == i:
        checkcode += chr(random.randrange(97,123))
    else:
        checkcode += str(random.randrange(0,10))
print(checkcode)

【4】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    输出用于分割文件路径的字符串,比如windows下的PATH分隔符为 ';',Linux下的PATH分隔符为':'
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所指向的文件或者目录的最后修改时间

 小技巧:字符串路径前加 'r' ,避免转义

其实 r 的作用和 \的作用一样,都是为了防止程序将 当作是转义字符,所以 和 在写的时候使用一种方法就可以,当然如果路径是 ,那么就不需要涉及这些了!

>>> import os
>>> os.getcwd()
'C:\Users\guochaoqun'
>>> os.chdir("c:\Users")
>>> os.getcwd()
'c:\Users'
>>> os.chdir(r"c:Users")
>>> os.chdir(r"c:Usersguochaoqun")
>>> os.getcwd()
'c:\Users\guochaoqun'

【5】SYS

sys.argv           命令行参数List,第一个元素是程序本身路径
sys.exit(n)        退出程序,正常退出时exit(0)
sys.version        获取Python解释程序的版本信息
sys.maxint         最大的Int值
sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform       返回操作系统平台名称
sys.stdout.write('please:')
val = sys.stdin.readline()[:-1]

【6】shutil(高级文件/目录操作)

shutil.copyfileobj(fsrc, fdst[, length])  # 将文件内容拷贝到另一个文件中,可以部分内容
shutil.copyfile(src, dst)                 # 拷贝文件
shutil.copymode(src, dst)                  # 仅拷贝权限。内容、组、用户均不变
shutil.copystat(src, dst)                  # 拷贝状态的信息,包括:mode bits, atime, mtime, flags
shutil.copy(src, dst)                      # 拷贝文件和权限
shutil.copy2(src, dst)                      # 拷贝文件和状态信息
shutil.copytree(src, dst, symlinks=False, ignore=None)    # 递归的去拷贝文件
shutil.rmtree(path[, ignore_errors[, onerror]])         # 递归删除文件
shutil.move(src, dst)  # 递归的去移动文件

shutil.make_archive(base_name, format,...)

创建压缩包并返回文件路径,例如:zip、tar

  • base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
    如:www                        =>保存至当前路径
    如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/
  • format: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”
  • root_dir: 要压缩的文件夹路径(默认当前目录)
  • owner: 用户,默认当前用户
  • group: 组,默认当前组
  • logger: 用于记录日志,通常是logging.Logger对象
#将 /Users/wupeiqi/Downloads/test 下的文件打包放置当前程序目录
 
import shutil
ret = shutil.make_archive("wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test')
 
 
#将 /Users/wupeiqi/Downloads/test 下的文件打包放置 /Users/wupeiqi/目录
import shutil
ret = shutil.make_archive("/Users/wupeiqi/wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test')

【7】用于序列化的两个模块(json & pickle)

用于序列化的两个模块

  • json,用于字符串 和 python数据类型间进行转换,通用的:dumps 出来就是字符串
  • pickle,用于python特有的类型 和 python的数据类型间进行转换:dumps 出来就是二进制

Json模块提供了四个功能:dumps、dump、loads、load

pickle模块提供了四个功能:dumps、dump、loads、load

   

【7.1】json

json 一般只适合简单的数据类型,比如字典、字符串、列表 等;

基本序列化与反序列化

序列化

复制代码
import json
# 什么叫序列化?把内存数据以指定格式 比如字符串存到文件
f = open('test.txt','w')
info = {
    'name':'alex',
    'age': 22
}
f.write(json.dumps(info))   # 同等于  json.dump(info,f)
f.close()
复制代码

反序列化

复制代码
import pickle
f = open("test.txt",'r')
data = json.loads(f.read())    # 同等于 data = json.load(f)
print(data)
print(data["age"])
f.close()
复制代码

【7.2】pickle

pickle 序列化与反序列化

序列化

复制代码
import pickle
# 什么叫序列化?把内存数据以指定格式 比如字符串存到文件
f = open('test.txt','wb')
info = {
    'name':'alex',
    'age': 22
}
f.write(pickle.dumps(info))   #pickle.dumps出来的是二进制,所以要用 wb ,同等于  pickle.dump(info,f)
f.close()
复制代码

反序列化

复制代码
import pickle
f = open("test.txt",'rb')
data = pickle.loads(f.read())     # 同等于  data = pickle.load(f)
print(data)
print(data["age"])
f.close()
复制代码

小技巧:可以多次dump和load,但必须一一对应,所以不建议!

 一般情况,只建议dump一次,load一次,如果想实现这个比较好的对应,那么建议使用 shelve模块

【8】shelve 

import shelve
import datetime
# 存储
d = shelve.open('test_shelve')  # 打开一个文件
info = {'age':22, 'job':'it'}
name = ["alex", "rain", "test"]

d["name"] = name  # 持久化列表
d["info"] = info  # 持久化字典
d["date"] = datetime.datetime.now()

d.close()

# 取出
d = shelve.open('test_shelve')
print(d.get("name"))
print(d.get("info"))
print(d.get("date"))
for get_info in d.items():   # 获取所有的条目
    print(get_info)
d.close()

还有很多方法 需要自己研究一下;

  

【9】xml处理模块

xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,不过,古时候,在json还没诞生的黑暗年代,大家只能选择用xml呀,至今很多传统公司如金融行业的很多系统的接口还主要是xml。

xml的格式如下,就是通过<>节点来区别数据结构的:

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank updated="yes">69</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>

xml协议在各个语言里的都 是支持的,在python中可以用以下模块操作xml   

import xml.etree.ElementTree as ET
 
tree = ET.parse("xmltest.xml")
root = tree.getroot()
print(root.tag)
 
#遍历xml文档
for child in root:
    print(child.tag, child.attrib)
    for i in child:
        print(i.tag,i.text)
 
#只遍历year 节点
for node in root.iter('year'):
    print(node.tag,node.text)

修改和删除xml文档内容

import xml.etree.ElementTree as ET
 
tree = ET.parse("xmltest.xml")
root = tree.getroot()
 
#修改
for node in root.iter('year'):
    new_year = int(node.text) + 1
    node.text = str(new_year)
    node.set("updated","yes")
 
tree.write("xmltest.xml")
 
 
#删除node
for country in root.findall('country'):
   rank = int(country.find('rank').text)
   if rank > 50:
     root.remove(country)
 
tree.write('output.xml')

自己创建xml文档

import xml.etree.ElementTree as ET
 
 
new_xml = ET.Element("namelist")
name = ET.SubElement(new_xml,"name",attrib={"enrolled":"yes"})
age = ET.SubElement(name,"age",attrib={"checked":"no"})
sex = ET.SubElement(name,"sex")
sex.text = '33'
name2 = ET.SubElement(new_xml,"name",attrib={"enrolled":"no"})
age = ET.SubElement(name2,"age")
age.text = '19'
 
et = ET.ElementTree(new_xml) #生成文档对象
et.write("test.xml", encoding="utf-8",xml_declaration=True)
 
ET.dump(new_xml) #打印生成的格式

【10】pyYMAL 配置文件模块

Python也可以很容易的处理ymal文档格式,只不过需要安装一个模块,参考文档:http://pyyaml.org/wiki/PyYAMLDocumentation 

【11】Re 正则模块   

常用正则表达式符号

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
'.'     默认匹配除 之外的任意一个字符,若指定flag DOTALL,则匹配任意字符,包括换行
'^'     匹配字符开头,若指定flags MULTILINE,这种也可以匹配上(r"^a"," abc eee",flags=re.MULTILINE)
'$'     匹配字符结尾,或e.search("foo$","bfoo sdfsf",flags=re.MULTILINE).group()也可以
'*'     匹配*号前的字符0次或多次,re.findall("ab*","cabb3abcbbac")  结果为['abb''ab''a']
'+'     匹配前一个字符1次或多次,re.findall("ab+","ab+cd+abb+bba") 结果['ab''abb']
'?'     匹配前一个字符1次或0
'{m}'   匹配前一个字符m次
'{n,m}' 匹配前一个字符n到m次,re.findall("ab{1,3}","abb abc abbcbbb") 结果'abb''ab''abb']
'|'     匹配|左或|右的字符,re.search("abc|ABC","ABCBabcCD").group() 结果'ABC'
'(...)' 分组匹配,re.search("(abc){2}a(123|456)c""abcabca456c").group() 结果 abcabca456c
 
 
'A'    只从字符开头匹配,re.search("Aabc","alexabc") 是匹配不到的
''    匹配字符结尾,同$
'd'    匹配数字0-9
'D'    匹配非数字
'w'    匹配[A-Za-z0-9]
'W'    匹配非[A-Za-z0-9]
's'     匹配空白字符、 、 、 , re.search("s+","ab c1 3").group() 结果 ' '
 
'(?P<name>...)' 分组匹配 re.search("(?P<province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{4})","371481199306143242").groupdict("city") 结果{'province''3714''city''81''birthday''1993'}

  

最常用的匹配语法

1
2
3
4
5
re.match 从头开始匹配
re.search 匹配包含
re.findall 把所有匹配到的字符放到以列表中的元素返回
re.splitall 以匹配到的字符当做列表分隔符
re.sub      匹配字符并替换

反斜杠的困扰
与大多数编程语言相同,正则表达式里使用""作为转义字符,这就可能造成反斜杠困扰。假如你需要匹配文本中的字符"",那么使用编程语言表示的正则表达式里将需要4个反斜杠"\\":前两个和后两个分别用于在编程语言里转义成反斜杠,转换成两个反斜杠后再在正则表达式里转义成一个反斜杠。Python里的原生字符串很好地解决了这个问题,这个例子中的正则表达式可以使用r"\"表示。同样,匹配一个数字的"\d"可以写成r"d"。有了原生字符串,你再也不用担心是不是漏写了反斜杠,写出来的表达式也更直观。

仅需轻轻知道的几个匹配模式

 
1
2
3
re.I(re.IGNORECASE): 忽略大小写(括号内是完整写法,下同)
M(MULTILINE): 多行模式,改变'^''$'的行为(参见上图)
S(DOTALL): 点任意匹配模式,改变'.'的行为

【12】configparser 配置文件模块(类似于my.cnf)

用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser。

来看一个好多软件的常见文档格式如下

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
 
[bitbucket.org]
User = hg
 
[topsecret.server.com]
Port = 50022
ForwardX11 = no

如果想用python生成一个这样的文档怎么做呢?

import configparser
 
config = configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval': '45',
                      'Compression': 'yes',
                     'CompressionLevel': '9'}
 
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '50022'     # mutates the parser
topsecret['ForwardX11'] = 'no'  # same here
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini', 'w') as configfile:
   config.write(configfile)

写完了还可以再读出来哈。

>>> import configparser
>>> config = configparser.ConfigParser()
>>> config.sections()
[]
>>> config.read('example.ini')
['example.ini']
>>> config.sections()
['bitbucket.org', 'topsecret.server.com']
>>> 'bitbucket.org' in config
True
>>> 'bytebong.com' in config
False
>>> config['bitbucket.org']['User']
'hg'
>>> config['DEFAULT']['Compression']
'yes'
>>> topsecret = config['topsecret.server.com']
>>> topsecret['ForwardX11']
'no'
>>> topsecret['Port']
'50022'
>>> for key in config['bitbucket.org']: print(key)
...
user
compressionlevel
serveraliveinterval
compression
forwardx11
>>> config['bitbucket.org']['ForwardX11']
'yes'

configparser增删改查语法

[section1]
k1 = v1
k2:v2
  
[section2]
k1 = v1
 
import ConfigParser
  
config = ConfigParser.ConfigParser()
config.read('i.cfg')
  
# ########## 读 ##########
#secs = config.sections()
#print secs
#options = config.options('group2')
#print options
  
#item_list = config.items('group2')
#print item_list
  
#val = config.get('group1','key')
#val = config.getint('group1','key')
  
# ########## 改写 ##########
#sec = config.remove_section('group1')
#config.write(open('i.cfg', "w"))
  
#sec = config.has_section('wupeiqi')
#sec = config.add_section('wupeiqi')
#config.write(open('i.cfg', "w"))
  
  
#config.set('group2','k1',11111)
#config.write(open('i.cfg', "w"))
  
#config.remove_option('group2','age')
#config.write(open('i.cfg', "w"))

【参考文档】

大部分转自:https://www.cnblogs.com/alex3714/articles/5161349.html

官网:https://docs.python.org/zh-cn/3.8/library/index.html

 
原文地址:https://www.cnblogs.com/gered/p/14000112.html