一、时间模块之一 time
1 #!/usr/bin/env python3 2 #author:Alnk(李成果) 3 import time 4 5 #时间表示的方式有如下3种: 6 #1.时间戳格式 7 #2.格式化时间字符串格式 8 #3.元组时间格式(共9个元素) 9 10 #小结: 时间戳格式 <---> 元组格式 <---> 格式化时间字符串格式 11 #时间戳格式和字符串格式之间不能直接转换 12 13 #时间戳 ---此刻时间减去1970年1月1日 00:00:00 14 # print(time.time()) #以时间戳格式获取本地当前时间 15 # print(time.time()/60/60/24/365) #距离1970年大约48年 16 # 17 # #时间戳 ---> 元祖格式时间 18 # print(time.localtime(time.time())) #把当前时间戳转化为本地时间的元祖格式--本地时区 19 # print(time.localtime(123123412)) #把123123412时间戳转化为本地时间的元祖格式--本地时区 20 # print(time.gmtime(time.time())) #把当前时间戳转化为标准时间的元祖格式--标准时区 21 # x = time.localtime(time.time()) # 22 # print(x.tm_year) #取出本地当前时间的年份,同理也可以取出年月日,时分秒等。 23 24 #元组时间格式 25 # print(time.localtime()) #以元组格式返回本地当前时间 26 # print(time.gmtime()) #以元组格式返回格林威治时间,相差8小时 27 28 #元祖格式 ---> 时间戳 29 # print(time.mktime(time.localtime())) #把本地当前元组格式的时间转化为时间戳格式的时间 30 # print(time.mktime(time.gmtime())) #把标准时间元组格式的时间转化为时间戳格式的时间 31 32 #元祖格式 ---> 格式化时间字符串格式 33 # print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())) #把本地当前时间(元组格式)转化为格式化字符串格式时间 34 35 #格式化时间字符串格式 ---> 元祖格式 36 # print(time.strptime("2018-08-03 20:06:33","%Y-%m-%d %H:%M:%S")) 37 38 #元祖格式 ---> 串 39 #print(time.asctime(time.localtime())) #接受的参数是元祖 40 41 #时间戳 --- > 串 42 #print(time.ctime(time.time())) 43 44 #本地标准时间与世界标准时间的差多少时间 45 # print(time.timezone) 46 # print(time.timezone/3600) 47 # print(time.sleep(1)) #停止1秒
二、时间模块之二 datetime
1 #!/usr/bin/env python3 2 #author:Alnk(李成果) 3 import datetime 4 """时间模块""" 5 # print(datetime.datetime.now()) #获取当前之间 6 # # 7 # print(datetime.datetime.now()+datetime.timedelta(3)) #3天后的时间 8 # print(datetime.datetime.now()+datetime.timedelta(-3)) #3天后的时间 9 # # 10 # print(datetime.datetime.now()+datetime.timedelta(hours=3)) #3小时后的时间 11 # print(datetime.datetime.now()+datetime.timedelta(hours=-3)) #3小时前的时间 12 # # 13 # print(datetime.datetime.now()+datetime.timedelta(minutes=3)) #3分钟后的时间 14 # print(datetime.datetime.now()+datetime.timedelta(minutes=-3)) #3分钟前的时间 15 # 16 #datetime对象 17 #dt = datetime.datetime.now() 18 # print(dt) 19 # print(dt.year) 20 # print(dt.month) 21 # print(dt.day) 22 # print(dt.hour) 23 # print(dt.minute) 24 # print(dt.second) 25 # print(dt.microsecond) #秒后面的单位 26 27 #date对象 28 # d = datetime.date.today() 29 # print(d.year) 30 # print(d.day) 31 # print(d.month) 32 33 #time对象 34 # t = datetime.time(dt.hour,dt.minute,dt.second) 35 # print(t.hour) 36 # print(t.minute) 37 # print(t.second)
三、随机数模块之 random
1 #!/usr/bin/env python3 2 #author:Alnk(李成果) 3 import random,string 4 # print(random.random()) #随机产生一个0-1之间的浮点数 5 # print(random.uniform(1,10)) #在1-10之间随机产生一个浮点数 6 # print(random.randint(1,10)) #随机产生1-10的整数,包括1和10 7 # print(random.randrange(1,10)) #随机产生1-10的整数,但是不包括10,顾头不顾尾 8 # print(random.choice('hello')) #从hello 这个字符串随机取一个值,也可以传入列表等序列 9 # print(random.choice([1,3,4])) 10 # print(random.sample('hello',2)) #随机产生两个值,可以传入序列 11 # 洗牌功能 12 # items = [1,2,3,4,5] 13 # print(items) 14 # random.shuffle(items) 15 # print(items) 16 # 17 # 实际应用 18 #1.随机整数 19 print(random.randint(0,99)) 20 # 21 #2.随机选取0-100的偶数 22 print(random.randrange(0,100,2)) 23 # 24 #3.随机浮点数 25 print(random.random()) 26 print(random.uniform(1,10)) 27 # 28 #4.随机字符 29 print(random.choice('abads234fasdf')) 30 # 31 #5.多个字符中选取特定数量的字符 32 print(random.sample('jadkfk4',3)) 33 # 34 #6.随机选取字符串 35 print(random.choice(['asdfa','cfadsfa','safc']))
小练习:6为随机验证码
1 #!/usr/bin/env python3 2 #author:Alnk(李成果) 3 import random 4 checkcode = '' 5 for i in range(6): 6 # 随机产生数字 7 if i == random.randint(0,5): 8 tmp = random.randint(0, 9) 9 elif i <= 2: 10 tmp = chr(random.randint(65,90)) #大写字母 11 else: 12 tmp = chr(random.randint(97,122)) #小写字母 13 checkcode +=str(tmp) 14 print(checkcode)
四、os模块
1 #!/usr/bin/env python3 2 #author:Alnk(李成果) 3 import os,time 4 #当前使用平台 5 #print(os.name) #windows -->nt linux -->posix 6 7 #当前路径和文件 8 #print(os.getcwd()) #返回当前文件所在的目录 9 #print(os.listdir(r"D:\04-python\day05\01笔记")) #显示01笔记这个文件夹的所有内容,包括隐藏文件 10 #print(os.listdir(os.getcwd())) #返回当前目录所有文件和目录 11 12 #绝对路径 13 #print(os.path.abspath(__file__)) 14 15 #如果文件或者目录是写的绝对路径,则返回True,否则为False 16 #print(os.path.isabs(r"c:\soft\b.txt")) 17 18 #向操作系统传递命令操作 19 #os.system("ls -l") #linux下的ls -l命令 20 21 #文件名和目录 22 #print(os.path.split(__file__)) #将目录名和文件名分开,返回值是一个元祖 23 #print(os.path.join(r"c:\soft",r"04-python",r"day09")) #路径拼接 24 #print(os.path.join(r"c:\soft",r"04-python",r"c:\day09")) #如果最后有绝对路径,则会覆盖之前的路径 25 #print(os.path.dirname(__file__)) #返回目录,不包含文件名 26 #print(os.path.basename(__file__)) #返回文件名,不包含目录 27 28 #创建目录 29 #os.mkdir("ostest") #只能创建一级目录,和linux的mkdir ostest有点像 30 #os.makedirs(r"mktest\a\b\c\d") #递归创建多级目录和linux的mkdir -p mktest\a\b\c\相似 31 32 #文件或者目录重命名 33 #os.rename("oldname","newname") #重命名文件/目录 34 35 #获取文件或者目录信息 36 #print(os.stat(r"./01电影分享.py")) 37 38 #删除文件或目录 39 #os.remove(r"ostest\1") #删除文件(必须是文件) 40 #os.rmdir(r"mktest\a\b\c\d") #只能删除一级目录,这里只能删除d目录 41 #os.removedirs(r"mktest\a\b\c") #递归删除目录,但是必须为空目录 42 43 #更改路径 44 # print(os.getcwd()) 45 # os.chdir("c:") 46 # print(os.getcwd()) 47 # os.chdir(os.path.dirname(__file__)) 48 # print(os.getcwd()) 49 50 #查看文件时间 51 # print(os.path.getmtime(__file__)) #返回文件或者目录的最后修改时间,结果为秒数 52 # print(time.localtime(os.path.getmtime(__file__))) #把上一步的时间转化为元祖格式时间 53 # print(os.path.getatime(__file__)) #返回文件或者目录的最后访问时间,结果为秒数 54 # print(time.localtime(os.path.getatime(__file__))) 55 # print(os.path.getctime(__file__)) #返回文件或者目录的创建时间,结果为秒数 56 # print(time.localtime(os.path.getctime(__file__))) 57 58 #查看文件大小 59 #print(os.path.getsize(__file__)) #单位为字节 60 #os.mkdir("ccc") 61 #print(os.path.getsize(r"ccc")) #如果为目录的话,目录下有其他文件则返回4096,空目录的话返回0 62 63 #判断文件和目录是否存在 64 #print(os.path.exists(r"c:\soft")) #判断目录是否存在,存在为True,反之为False 65 #print(os.path.exists("08os模块.py")) #判断文件是否存在,存在为True,反之为False 66 #print(os.path.isfile("08os模块.py")) #判断是否为一个文件,是为True,其他为False 67 #print(os.path.isdir(r"c:\soft1")) #判断是否为一个目录,是为True,其他为False 68 69 #表现形式参数 70 #print(os.sep) #返回当前操作系统的特定路径分割符,windows -->\ linux -->/ 71 #print(os.linesep) #返回当前平台使用的行终止符, win下为"\r\n",linux为"\n" 72 #print(os.pathsep) #返回用于分割文件路径的字符串 win下为:";",linux为":" 73 74 #查看系统环境变量 75 #print(os.environ) #查看当前系统的环境变量 76 77 #返回当前目录和上一级目录 78 #print(os.curdir) 79 #print(os.pardir)
五、sys模块
1 #!/usr/bin/env python3 2 #author:Alnk(李成果) 3 import sys 4 #sys.argv #命令行参数list,第一个元素是程序本身,参数从 sys.argv[1] 开始 5 #print(sys.version) #获取python解释程序的版本信息 6 #sys.exit("quit") #退出程序 7 #print(sys.maxsize) #最大的值 8 #print(sys.path) #返回模块搜索路径,初始化时使用PYTHONPATH环境变量值 9 #print(sys.platform) #返回操作系统平台名称 10 #print(sys.modules ) #返回所有已经导入的模块列表,是一个字典格式 11 12 #标准输入 13 # print("please input you name>>>:") 14 # name = sys.stdin.readline() 15 # print(name) 16 17 #标准输出 18 #sys.stdout.write("123456\n") 19 #sys.stdout.flush()
六、shutil模块
1 #!/usr/bin/env python3 2 #author:Alnk(李成果) 3 import shutil 4 """高级的文件,文件夹处理模块""" 5 6 #copy 08os模块.py 为test2 7 # f1 = open("08os模块.py",encoding="utf-8") 8 # f2 = open("test2","w",encoding="utf-8") 9 # shutil.copyfileobj(f1,f2) 10 11 #只拷贝文件内容 12 #shutil.copyfile("09sys模块.py","test3") 13 14 #复制文件和权限 15 #shutil.copy() 16 17 #拷贝文件和状态信息 18 #shutil.copy2() 19 20 #仅拷贝权限。内容、组、用户均不变(前提是源文件和目标文件都必须存在不然会报错) 21 #shutil.copymode("08os模块.py","dst.py") 22 23 #拷贝文件的状态信息 如:atime,ctime,mtime,mode bits属性 24 #shutil.copystat() 25 26 #递归复制文件夹 27 # shutil.copytree("src","dst") 28 29 #递归删除目录 30 # shutil.rmtree() 31 32 #移动递归去移动文件,类似mv命令,其实就是重命名 33 #shutil.move('folder1', 'folder3') 34 35 #压缩 36 #下面这个例子的意思是把D:\\04-python\\day01这个文件夹压缩到当前目录,压缩后的文件名称为:shutil_archive_test.zip 37 #"shutil_archive_test" ---默认路径为当前目录 38 #shutil.make_archive("shutil_archive_test","zip","D:\\04-python\\day01") 39 40 41 #shutil压缩调用的是zipfile和tarfile模块来实现功能的。单独压缩一个一个的文件 42 import zipfile 43 #压缩 44 # z = zipfile.ZipFile('alnk.zip','w') 45 # z.write('atest.txt') 46 # z.write('btest.txt') 47 # z.close() 48 #解压 49 # z = zipfile.ZipFile('alnk.zip','r') 50 # z.extractall() #会覆盖命名相同的文件 51 # z.close() 52 53 import tarfile 54 #打包 55 # tar = tarfile.open('alnk.tar','w') 56 # tar.add('atest.txt',arcname='atest.txt') 57 # tar.add('btest.txt') 58 # tar.close() 59 #解包 60 # tar = tarfile.open('alnk.tar','r') 61 # tar.extractall() #会覆盖原文件 62 # tar.close()
小练习:win系统下压缩文件
1 #!/usr/bin/env python3 2 #coding=utf-8 3 #author:Alnk(李成果) 4 #该脚本备份的时候,如果有文件存在加密,则可能会导致备份失败 5 import shutil,time,os,sys 6 #源文件目录 7 src_dir = "C:\\caiwu_share" 8 if not os.path.isdir(src_dir): 9 sys.exit("源文件目录不存在") 10 11 #目标文件 12 date = time.strftime("%Y%m%d%H%M%S",time.localtime()) 13 det_dir = "D:\\财务数据备份\\"+date 14 15 #压缩 16 if not os.path.isfile(det_dir+".zip"): 17 shutil.make_archive(det_dir, "zip", src_dir) 18 else: 19 sys.exit("目标文件已经存在")
七、shelve模块
1 #!/usr/bin/env python3 2 #author:Alnk(李成果) 3 import shelve,datetime 4 """一个简单的k,v将内存数据通过文件持久化的模块,持久化任何pickle可支持的python数据格式""" 5 6 #写入数据 7 # f = shelve.open("shelve_test.txt") 8 # info = {"name":"alnk","age":19,} 9 # l1 = ["name","age","job"] 10 # l2 = [] 11 # f["dict1"] = info 12 # #f["list1"] = l1 13 # f['list1'] = l2 14 # f["date"] = datetime.datetime.now() 15 #f.close() 16 # 17 #读取数据 18 # f = shelve.open("shelve_test.txt") 19 # # #读取所有数据 20 # # for k,v in f.items(): 21 # # print(k,v) 22 # # 23 # # #读取某个key-vlues 24 # # print(f.get("dict1")) 25 # # print(f.get("list1")) 26 # # print(f.get("date")) 27 # # f.close() 28 #详情可以看一下链接 29 #https://blog.csdn.net/u012145252/article/details/80028146
八、xml模块
1 #!/usr/bin/env python3 2 #author:Alnk(李成果) 3 import xml.etree.ElementTree as ET 4 """ 5 xml是实现不同国语言活程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单, 6 不过,以前,在json没诞生的时候,只能用xml,所以至今很多传统公司如金融行业的很多系统 7 接口主要还是xml。 8 xml就是通过 < > 节点来区别数据结构的 9 """ 10 11 tree = ET.parse("xmltest.xml") 12 root = tree.getroot() 13 print(root) #xmltest.xml data的内存地址 14 print(root.tag) #标签 15 16 #遍历xml文档 17 for child in root: 18 print(child.tag,child.attrib) 19 for i in child: 20 print(i.tag,i.text,i.attrib) 21 #只遍历year 节点 22 for node in root.iter('year'): 23 print(node.tag,node.text)
1 #!/usr/bin/env python3 2 #author:Alnk(李成果) 3 import xml.etree.ElementTree as ET 4 5 tree = ET.parse("xmltest.xml") 6 root = tree.getroot() 7 8 #修改 9 # for node in root.iter('year'): 10 # new_year = int(node.text) + 1 11 # node.text = str(new_year) 12 # node.set("updated","yes") 13 # tree.write("xmltest.xml") 14 15 #删除node 16 for country in root.findall('country'): 17 rank = int(country.find('rank').text) 18 if rank >50: 19 root.remove(country) 20 tree.write("xmltest.xml")
1 #!/usr/bin/env python3 2 #author:Alnk(李成果) 3 import xml.etree.ElementTree as ET 4 5 new_xml = ET.Element("personinfolist") 6 personinfo = ET.SubElement(new_xml, "personinfo", attrib={"enrolled": "yes"}) 7 name = ET.SubElement(personinfo, "name") 8 name.text = "Alex Li" 9 age = ET.SubElement(personinfo, "age", attrib={"checked": "no"}) 10 sex = ET.SubElement(personinfo, "sex") 11 age.text = '56' 12 personinfo2 = ET.SubElement(new_xml, "personinfo", attrib={"enrolled": "no"}) 13 name = ET.SubElement(personinfo2, "name") 14 name.text = "Oldboy Ran" 15 age = ET.SubElement(personinfo2, "age") 16 age.text = '19' 17 18 et = ET.ElementTree(new_xml) # 生成文档对象 19 et.write("test.xml", encoding="utf-8", xml_declaration=True) 20 21 ET.dump(new_xml) # 打印生成的格式
九、PyYAML模块
1 #!/usr/bin/env python3 2 #author:Alnk(李成果) 3 import yaml 4 """该模块需要自己安装 pip install pyyaml,该模块主要用来解析yaml格式的配置文件""" 5 f = open("login.yaml",encoding="utf-8") 6 res = yaml.load(f) 7 print(type(res)) 8 print(len(res)) 9 print(res) 10 for i in res: 11 print(type(i)) 12 print(i)
十、configparser模块
1 #!/usr/bin/env python3 2 #author:Alnk(李成果) 3 import configparser 4 """用于生成和修改常见的配置文档""" 5 6 #生成一个文件 7 # config = configparser.ConfigParser() 8 # 9 # config["DEFAULT"] = {'ServerAliveInterval': '45', 10 # 'Compression': 'yes', 11 # 'CompressionLevel': '9'} 12 # config['DEFAULT']['ForwardX11'] = 'yes' 13 # 14 # config['bitbucket.org'] = {} 15 # config['bitbucket.org']['User'] = 'hgalnk' 16 # 17 # config['topsecret.server.com'] = {} 18 # config['topsecret.server.com']['Host Port'] = '50022' 19 # config['topsecret.server.com']['ForwardX11'] = 'no' 20 # 21 # with open('example.ini', 'w') as configfile: 22 # config.write(configfile) 23 24 #读取 25 # config = configparser.ConfigParser() 26 # print(config.sections()) 27 # 28 # config.read("example.ini") 29 # 30 # print(config.sections()) #默认的没有读出来 31 # print(type(config)) 32 # print('bitbucket.org' in config) 33 # 34 # print(config['bitbucket.org']['User']) 35 # print(config['DEFAULT']['compression']) 36 # 37 # topsecret = config['topsecret.server.com'] 38 # print(topsecret['host port'])
1 #!/usr/bin/env python3 2 #author:Alnk(李成果) 3 import configparser 4 config = configparser.ConfigParser() 5 6 #读取 7 configparser.ConfigParser().read('i.cfg') 8 # config.read("i.cfg") 9 # secs = config.sections() 10 # print(type(secs)) 11 # print(secs) 12 # 13 # options = config.options('section2') 14 # print(type(options)) 15 # print(options) 16 17 # item_list = config.items('section2') 18 # print(type(item_list)) 19 # print(item_list) 20 21 # va1 = config.get('section1','k2') 22 # print(type(va1)) 23 # print(va1) 24 25 # va2 = config.get('section2','k1') 26 # print(type(va2)) 27 # print(va2) 28 29 #改写 30 #删除section1整个节点 31 # sec = config.remove_section('section1') 32 # config.write(open('i.cfg','w')) 33 34 #新建节点 35 # sec = config.has_section('alnk') #判断有没有alnk节点 36 # sec1 = config.add_section('alnk') #增加alnk这个节点 37 # config.write(open('i.cfg','w')) #写入到文件中 38 39 #节点下面添加选项 40 # config.set('alnk','k1','123456') #注意值必须为字符串,'123456' 41 # config.write(open('i.cfg','w')) 42 43 #删除节点下面的选项 44 # config.remove_option('alnk','k1') 45 # config.write(open('i.cfg','w'))
十一、hashlib模块
1 #!/usr/bin/env python3 2 #author:Alnk(李成果) 3 import hashlib 4 """用于加密,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法""" 5 m1 = hashlib.md5() 6 m1.update(b'hello') 7 m1.update(b"it's me") 8 print(m1.hexdigest()) #十六进制加密,32位长度 9 print(len(m1.hexdigest())) 10 11 m = hashlib.md5() 12 m.update("hello中文".encode(encoding="utf-8")) 13 print(m.hexdigest())
十二、re模块
1 #!/usr/bin/env python3 2 #author:Alnk(李成果) 3 import re 4 """正则匹配""" 5 6 """ 7 '.' 默认匹配除\n之外的任意一个字符,若指定flag DOTALL,则匹配任意字符,包括换行 8 '^' 匹配字符开头,若指定flags MULTILINE,这种也可以匹配上(r"^a","\nabc\neee",flags=re.MULTILINE) 9 '$' 匹配字符结尾,或e.search("foo$","bfoo\nsdfsf",flags=re.MULTILINE).group()也可以 10 '*' 匹配*号前的字符0次或多次,re.findall("ab*","cabb3abcbbac") 结果为['abb', 'ab', 'a'] 11 '+' 匹配前一个字符1次或多次,re.findall("ab+","ab+cd+abb+bba") 结果['ab', 'abb'] 12 '?' 匹配前一个字符1次或0次 13 '{m}' 匹配前一个字符m次 14 '{n,m}' 匹配前一个字符n到m次,re.findall("ab{1,3}","abb abc abbcbbb") 结果'abb', 'ab', 'abb'] 15 '|' 匹配|左或|右的字符,re.search("abc|ABC","ABCBabcCD").group() 结果'ABC' 16 '(...)' 分组匹配,re.search("(abc){2}a(123|456)c", "abcabca456c").group() 结果 abcabca456c 17 '\A' 只从字符开头匹配,re.search("\Aabc","alexabc") 是匹配不到的 18 '\Z' 匹配字符结尾,同$ 19 '\d' 匹配数字0-9 20 '\D' 匹配非数字 21 '\w' 匹配[A-Za-z0-9] 22 '\W' 匹配非[A-Za-z0-9] 23 's' 匹配空白字符、\t、\n、\r , re.search("\s+","ab\tc1\n3").group() 结果 '\t' 24 """ 25 26 # re.match 从头开始匹配 27 # re.search 匹配包含 28 # re.findall 把所有匹配到的字符放到以列表中的元素返回 29 # re.split 以匹配到的字符当做列表分隔符 30 # re.sub 匹配字符并替换 31 32 #几个简单的例子 33 #re.match 34 # m = re.match("[0-9]+","alnk123ccc") 35 # if m: 36 # print(m.group()) #此处没有匹配到123是因为match从头开始匹配 37 38 #re.search #匹配整个字符串,但是只要匹配到第一个就结束了 39 # m2 = re.search("[0-9]+","alnk123ccc123bbb") 40 # if m2: 41 # print(m2.group()) 42 43 #re.findall #匹配所有符合条件的字符串 44 # m2 = re.findall("[0-9]+","alnk123ccc123bbb") 45 # print(m2) 46 47 #re.split 以匹配到的字符当做列表分隔符 48 # m2 = re.split("[0-9]+","alnk123ccc123bbb") 49 # print(m2) 50 51 #re.sub 匹配字符并替换 52 # m2 = re.sub("[0-9]+",'#####',"alnk123ccc123bbb") 53 # print(m2) 54 55 #忽略大小写 56 # m1 = re.findall("a","abbbAccc",flags=re.I) 57 # m2 = re.findall("a","abbbAccc",flags=re.IGNORECASE) 58 # print(m1,m2) 59 60 #分组匹配 61 # m2 = re.search("(?P<province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{4})","371481199306143242") 62 # if m2: 63 # print(m2.groupdict()) 64 #可以用来匹配身份证 65 # m3 = re.search("(?P<province>[0-9]{2})(?P<city>[0-9]{2})(?P<county>[0-9]{2})(?P<year>[0-9]{4})(?P<month>[0-9]{2})(?P<day>[0-9]{2})(?P<number>[0-9]{4})","411221199708303233") 66 # if m3: 67 # print(m3.groupdict())