python学习道路(day6note)(time &datetime,random,shutil,shelve,xml处理,configparser,hashlib,logging模块,re正则表达式)

时间:2023-03-09 01:20:12
python学习道路(day6note)(time &datetime,random,shutil,shelve,xml处理,configparser,hashlib,logging模块,re正则表达式)

1.tiim模块,因为方法较多我就写在code里面了,后面有注释

 #!/usr/bin/env python
 #_*_coding:utf-8_*_

 print("time".center(60,"-"))
 print(time.asctime())   #返回字符串格式 外国的时间
 #Fri Nov 18 11:25:08 2016
 t = time.localtime()    #本地时间
 #print(t)  #这是一个对象所以需要
 print(t.tm_year,t.tm_yday)
 #time.struct_time(tm_year=2016, tm_mon=11, tm_mday=18, tm_hour=11, tm_min=25, tm_sec=8, tm_wday=4, tm_yday=323, tm_isdst=0)
 print(time.time())   #print(time.time()/(3600*24*365))   算年
 #1479439871.1401508 时间戳
 print(time.gmtime())   #utc 时间
 t = time.localtime(time.time() + 3600*3)    #改变时间,针对秒做运算
 print(t)
 print(time.asctime(t)) #返回当前时间并且,需要的时间对象
 print(time.ctime()) #返回当前时间,同上

 #字符串转时间戳
 print(time.strptime("2016-11-11 23:30","%Y-%m-%d %H:%M")) #转成时间对象了
 t2 = time.strptime("2016-11-11 23:30","%Y-%m-%d %H:%M") #时间戳
 print(time.mktime(t2))

 #时间戳转字符串
 t2_stamp = time.mktime(t2)  #时间戳
 print(t2_stamp)
 t3 = time.localtime(t2_stamp)  #时间对象
 t3_str = time.strftime("%Y_%m_%d_%H_%M.log",t3)  #日志时间格式
 print(t3_str)

2.datetiim模块,因为方法较多我就写在code里面了,后面有注释

 #!/usr/bin/env python
 #_*_coding:utf-8_*_

 ###datetime
 #时间加减    可以对天 分钟 小时进行计算
 print("datetime".center(60,"-"))
 print(datetime.datetime.now())
 print(datetime.datetime.fromtimestamp(time.time()-3600))
 print(datetime.datetime.now() - datetime.timedelta(days=3)) #day hours mintes 前面的 + -控制加减

 now = datetime.datetime.now() #可以直接替换时间
 print(now.replace(month=1,day=3,hour=3))

3.random模块,因为方法较多我就写在code里面了,后面有注释

#!/usr/bin/env python
#_*_coding:utf-8_*_

print("random".center(60,"-")) #随机数模块
import random
print(random.random()) #随机打印一个小数
print(random.randint(1,2))#包含
print(random.randrange(1,10))#不包含后面值
print(random.sample(range(100),5)) #随机数密码
print(random.sample('abcde',2))

import string
str_sourc = string.ascii_letters + string.digits
print(''.join(random.sample(str_sourc,6)))  #join好像是可以把列表拆开成字符串
##随机数脚本
import random
checkcode = ''
for i in range(4):
    current = random.randrange(0,4)
    if current != i:
        temp = chr(random.randint(65,90))  #65-90 就是ansi码对应的A-Z的大写
    else:
        temp = random.randint(0,9)
    checkcode += str(temp)
print(checkcode)  #生成四位的随机数

3.shutil模块,因为方法较多我就写在code里面了,后面有注释

 #!/usr/bin/env python
 #_*_coding:utf-8_*_

 #高级的文件,文件夹,压缩包,处理模块
 import shutil
 #f1 = open("file_old.txt")
 #f2 = open("file.new.txt",'w')
 #shutil.copyfileobj(f1, f2)#因为是对象,所以你要先打开文件
 #os.path.basename("/var/www/data1") 文件名最后显示data1
 #os.path.join("/usr/local/data1")
 #shutil.copy(r"c:笔记","test") #会拷贝到当前目录 上面2条是解释相当于  不需要打开文件
 #copy 与 copyfile的区别在于,copy是会把权限copy过来
 #shutil.copyfile(r"c:笔记","test")
 #shutil.copy2()  #拷贝文件和状态
 #shutil.copytree(r"c:笔记","新笔记") #cp -rf拷贝目录过来
 #shutil.rmtree()秭归删除
 #shutil.move()移动

 # 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对象
 #shutil.make_archive(r"c:笔记",format="zip",root_dir=r"c:新笔记")

4.shelve模块,因为方法较多我就写在code里面了,后面有注释

 #!/usr/bin/env python
 #_*_coding:utf-8_*_

 print("shelve".center(60,"-")) #是一个简单的k,v将内存数据通过文件持久化的模块,可以持久任何pickle
 #可支持的Python数据格式
 # import shelve
 # d = shelve.open('shelve_test')  # 打开一个文件
 # def stu_data(name,age):
 #     print("register stu",name,age)
 # name = ["alex", "rain", "test"]
 # d["test"] = name  # 持久化列表
 # d['func'] = stu_data #内存地址    相当于 2个类型存储  然后用下面的来读取下来
 # d.close()
 # #执行过后会出现三个文件
 #
 # #应该新打开一个文件来load
 # import shelve
 # def stu_data(name,age):#加上就不会报错
 #     print("register stu",name,age)  #加上就不会报错
 # f = shelve.open("shelve_test")
 # print(f["test"])  #打印出来的是 三个名字
 # print(f["func"]("test,30"))  #会打印不出来,因为func是内存地址,dump的话找对象找不到

5.xml处理模块,因为方法较多我就写在code里面了,后面有注释

 #!/usr/bin/env python
 #_*_coding:utf-8_*_

 print("xml".center(60,"-"))
 # import xml.etree.ElementTree as ET
 # tree = ET.parse("test.xml")
 # root = tree.getroot() #根节点 data
 # 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)

5.hashlibl处理模块,因为方法较多我就写在code里面了,后面有注释

 #!/usr/bin/env python
 #_*_coding:utf-8_*_

 print("hashlib".center(60,"-"))   #一种跟md5相同的效验工具
 import hashlib
 m = hashlib.md5()
 m.update(b"alex")
 print(m.hexdigest())    #md5值
 m.update(b"li")
 print(m.hexdigest())
 m2 = hashlib.md5()
 m2.update(b"alexli")
 print(m2.hexdigest())  #md5竟然是相同的

 m3 = hashlib.sha256()  #一般比较安全就256
 m3.update(b"alexli")
 print(m3.hexdigest())

 import hmac
 h = hmac.new(b'salt',b'hello')
 print(h.hexdigest())  #这个更安全,一般用于网络上的消息加密传输

6.loggingl处理模块,因为方法较多我就写在code里面了,后面有注释

 #!/usr/bin/env python
 #_*_coding:utf-8_*_

 print("logging".center(60,"-"))
 import logging

 logging.debug("test debug")
 logging.info("test info")
 logging.warning("this wron plees zhuyi")
 logging.error("test error")
 logging.critical("server is down")  #默认warining 以下不打印

 import logging
 logging.basicConfig(filename='example.log',level=logging.DEBUG) #打印到文件里面   报警的文件需要放在这下面才能生成
 logging.basicConfig(filename='example.log',level=logging.DEBUG,format='%(asctime)s %(message)s',datefmt='%m/%d/%Y %I:%M:%S %p')#加入了时间
 #format()参数里面可以加入级别各种日志格式  可以加一些分隔符 :-等

7.re正则,因为方法较多我就写在code里面了,后面有注释

 #!/usr/bin/env python
 #_*_coding:utf-8_*_

 a = re.match("inet","inet address:10.10.10.10 netmask:20.20.20.20")  #前面引号是规则  match是从头开始匹配
 print(a)  #
 print(a.group())#规则是4个所以显示就是四个
 #规则地方写入"\w+"  \w匹配一个字符[a-zA-Z0-9]  \w+匹配多个
 #'.' 匹配除了\n外的任意一个字符,包括特殊字符
 #'+' 匹配前一个字符一个或者多个
 #'^' 匹配字符开头 但是match就是匹配开头,所以没啥意义
 #'*' 匹配*号前的字符0次或多次   言外之意就是可以匹配不到  会返回空
 #'?' 匹配字符一次或者0次 不能多
 #'{m}' 匹配前一个字符m次  "\w{3}"
 #'{n,m}' 匹配前一个字符多少到多少次  "\w{5,8}"
 #'|' 匹配左边或右边的字符  "inet|INET"
 #(...) 分组匹配
 # print(re.search("(\d){2}(\d){2}(\d){2}","123456789 name:alex").group()) #这是匹配出来的结果 123456
 # print(re.search("(\d){2}(\d){2}(\d){2}","123456789 name:alex").groups()) #2 4 6
 # print(re.search("(\d\d)(\d\d)(\d\d)","123456789 name:alex").groups()) #12 34 56
 # print(re.search("(\d{2})(\d{2})(\d{2})","123456789 name:alex").groups())
 #'\A' 只从字符开头匹配
 #'\z' 以数字结尾 同$
 #'\d' 匹配0-9
 #'\D' 匹配非数字
 #'\w' 匹配[a-zA-Z0-9]
 #'\W' 匹配非[a-zA-Z0-9]  就是特殊字符
 #'s' 匹配空白字符 ,\t \n \r
 #'(?P<name>...)' #分组匹配
 ").groupdict())
 #groupdic() 字典形式  groups()列表
 print(re.search("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}","inet address:10.10.10.10 netmask:20.20.20.20"))
 print(re.search("(\d{1,3}\.){3}\d{1,3}","inet address:10.10.10.10 netmask:20.20.20.20"))
 print(re.findall("\d+","a555b3c5d6s"))  #search 是匹配到了第一个就开始返回了,而findall是匹配所有了
 print(re.findall("[a-z]","a555b3c5d6s"))

 print(re.split("\d+","a555b3c5d6s6"))    #split也是数字作为分隔符,但是侯后面会多出一个元素
 print(re.sub("\d+","|","a555b3c5d6s6"))  #匹配字符替换  以什么为分隔符给替换
 print(re.sub("\d+","|","a555b3c5d6s6",count=2))

 #反斜杠的困扰  比如目录格式
 print(re.split("\\\\",r"c:\users\data\python35"))  #加r就是字符串对待  这是以\为分隔符
 print(re.search("a","ABC",flags=re.I))   #re.I 忽律大小写
 print(re.search("^a","\nabc\neee",flags=re.M))  #re.M 匹配多行要不\n就换行
 print(re.search(".+","\nabc\neee",flags=re.S))  #多行都匹配出来而且\n也匹配出来

8.configparser正则,因为方法较多我就写在code里面了,后面有注释