Python学习之路第五周汇总

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author:Source
import shutil
#shutil模块
# f = open('test','w')
# f.write("测试文本")
# f.closed
# f1 = open('test','r')
# f2 = open('copyfileobj_test','w')
# shutil.copyfileobj(f1,f2)#将文件内容拷贝高另一个文件中,可以部分内容,文件事先要存在。
# shutil.copyfile('test','copyfile_test')#拷贝文件
# shutil.copymode('test','copymode_test')#仅仅拷贝权限。内容、组、用户均不变化,文件事先要存在。
# shutil.copystat('test','copystat_test')#拷贝状态信息,包括mode bits,atime,mtim# e,flags
# shutil.copy('test','copy_test')#拷贝文件和权限
# shutil.copy2('test','copy2_test')#拷贝文件和状态信息
# shutil.copytree("C:/Users/ys106/PycharmProjects/Source/day4/homework/ATM_Program",'C:/Users/ys106/PycharmProjects/Source/day5/homework/copytree_test')#递归的去拷贝文件
# shutil.rmtree('copytree_test')#递归的去删除文件
#shutil.move('C:/Users/ys106/PycharmProjects/Source/day5/homework/copytree_test','C:/Users/ys106/PycharmProjects/Source/day4/homework/move_test')
#shutil.make_archive("backups/ATM/make_archive_test","zip",'C:/Users/ys106/PycharmProjects/Source/day4/homework/ATM_Program')#创建压缩包并返回文件路径
#shutil.make_archive实际上是调用了ZipFile和TarFile两个模块来进行的
#压缩
# z = zipfile.ZipFile("Zipfile_test.zip","w")
# z.write('test')
# print("可以中断一下")
# z.write("copy_test")
# z.close()

#解压
# z= zipfile.ZipFile('Zipfile_test.zip','r')
# z.extractall('C:/Users/ys106/PycharmProjects/Source/day5/homework/zipfile')#可以指定目录
# z.close()
# shutil.rmtree("C:/Users/ys106/PycharmProjects/Source/day5/homework/zipfile")
# homeword_ATM = zipfile.ZipFile('backups/ATM/make_archive_test.zip','r')
# homeword_ATM.extractall("C:/Users/ys106/PycharmProjects/Source/day5/homework/backups/ATM")
# #shutil.rmtree("C:/Users/ys106/PycharmProjects/Source/day5/homework/backups/ATM/Users")
# homeword_ATM.close()
#压缩
'''tar = tarfile.open('tarfile.tar','w')
tar.add('test',arcname = 'tarfile_test.zip')
tar.close()#不知道为什么生成不了压缩文件
#解压
tar = tarfile.open("tarfile.tar",'r')
tar.extractall("C:/Users/ys106/PycharmProjects/Source/day5/homework/backups")
tar.close()'''#存在bug,压缩文件打不开
#常用模块的学习,模块的定义是:本质上是一个以.py结尾的python文件(文件名:test.py 模块名:test)。
#包定义:是用来逻辑组织模块,本质上是一个文件夹(必须带一个_init_.py文件)
#模块的作用:是用来逻辑上组织python代码(变量,函数,类,逻辑:实现一个功能)
# 导入方法:import module_name
# import module_name,module2_name
# form module_alex import*
# from module_alex import m1,m2,m3
# from module_alex import logger as logger_alex
import os
import sys
to_lead_other_addr = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
#print(to_lead_other_addr)
sys.path.append(to_lead_other_addr)
import areyourready
#相对导入 form.import test1的使用?导入包与__init__同一级目录
#import本质:
#先将模块内的所有文件解释一遍并赋值给一个变量,导入时候要加上变量名再加点进行调用
#from import本质:
#打开文件,找到变量,变量拿到当前位置执行一遍
#导入包的本质:
#执行包下的__init.py__文件
#导入优化:
import time
# print(time.time())#用秒进行时间的表示
# print(time.timezone)#本地时间与UTC世界标准时间的差值
# print(time.ctime(time.time()))#格式化显示时间,传入的是时间戳
# print(time.daylight)#判断是否使用夏时制,否为0
# #print(time.sleep(1))#起延时作用
# print(time.gmtime(time.time()))#传入的是时间戳
# print(time.gmtime())#不传数据,显示UTC标准时间
# print(time.localtime())#显示当地时区时间,中国UTC+8,传值按秒的形式
# x = time.localtime()
# print(x.tm_mday)#取出个别,gmtime()也类似
# print(time.mktime(time.localtime()))#将元组形式的时间转化为秒的形式
# print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))#传入的元组的是元组的形式
# print(time.strptime("2018-10-29 16:17:29","%Y-%m-%d %H:%M:%S"))
# t = (2018,10,29,17,6,28,0,302,0)
# print(time.asctime(t))#传入的是元组
# print(time.asctime())
import datetime
# 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 = 2))#当前时间+2小时
# print(datetime.datetime.now()+datetime.timedelta(minutes = -10))#当前使间-10分钟
# c_time = datetime.datetime.now()
# print(c_time.replace(hour=8,minute=10))#更改时间
import random
print(random.random())#随机的0-1的浮点数
print(random.randint(0,50))#随机指定的整数
print(random.randrange(0,50,2))#随机选取0-50的奇数
tuple = (1,6,7,9)
print(random.choice(tuple))#随机取一个值,可以传入元组、字符串、列表等
print(random.sample("source",2))#前面定义序列,后面定义取的位数
print(random.uniform(1,10))#指定随机取的范围
items = [2,4,8,6,15,10]
random.shuffle(items)#洗牌,打乱顺序
print(items)
print(os.getcwd())#获取当前工作目录
#print(os.chdir())#改变当前脚本的工作目录,可以采用两个斜杆或者在路径前加一个'r'的方式
print(os.curdir)#返回当前目录.
print(os.pardir)#返回上一级目录..
os.makedirs(r"C:\Users\ys106\PycharmProjects\Source\day5\homework\os_test\hello")#递归地去创建一个目录,即使不存在。
#shutil.rmtree("C:\\Users\\ys106\\PycharmProjects\\Source\\day5\\homework\\os_test")
os.removedirs("C:\\Users\\ys106\\PycharmProjects\\Source\\day5\\homework\\os_test\\hello")#若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,以此类推
#os.mkdir(),生成单级目录;相当于shell中mkdir dirname
#os.mkdir('mkdir_test/test')
#os.rmdir(),删除单级空目录,若目录不为空则无法删除,报错;相当于shell中的 rmdir dirname
#os.rmdir('mkdir_test/test')
#os.listdir(),列除指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印。
print(os.listdir('test_from_point_import'))
#os.remove() 删除一个文件
#os.remove('mkdir_test/remove_test')#似乎必须是文件
#os.rename() 重命名文件/目录
#os.rename('mkdir_test','new_name')
#os.stat() 获取文件/目录信息
print(os.stat('test_from_point_import'))
#os.sep,输出操作系统特定的路径分隔符,win下为"\\",linux下为“/”
print(os.sep)
#os.linesep,输出当前平台使用的行终止符,win下为“\t\n”,Linux下为“\n”
print(os.linesep)
#os.name,输出字符串指示当前使用平台。win->"nt";Linux->"posix"
print(os.name)
#os.system(),运行shell命令,直接显示
print(os.system('dir'))
#os.environ,获取系统环境变量
print(os.environ)
#os.path.abspath(path),返回path规范化的绝对路径
print(os.path.abspath(__file__))
#os.path.split(path),将path分割成目录和文件名二元组返回
print(os.path.split('test_from_point_import'))
#os.path.basename(path),返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。
print(os.path.basename(os.path.abspath(__file__)))
#os.path.dirname(path),返回path的目录。其实就是os.path.split(path)的第一个元素
print(os.path.dirname(os.path.abspath(__file__)))
#os.path.exists(path),如果path存在,返回True;如果path不存在,返回False
print(os.path.exists(os.path.dirname(os.path.abspath(__file__))))
#os.path.isabs(path),如果path是绝对路径,返回True
print(os.path.isabs("C:\\Users\\ys106\\PycharmProjects\\"))
#os.path.isdir(path),如果path是一个存在的目录,则返回True.否则,返回False。
print(os.path.isdir("C:\\Users\\ys106\\PycharmProjects\\a"))
#os.path.isfile(path),如果path是一个存在的文件,返回True。否则返回False。
print(os.path.isfile("test_from_point_import\\test_point.py"))#后缀也必须要加上
#os.path.join(),将多个路径组合后返回,会从第一个以”/”开头的参数开始拼接,之前的参数全部丢弃.在上一种情况确保情况下,若出现”./”开头的参数,会从”./”开头的参数的上一个参数开始拼接。
print(os.path.join('/json','\\dir','python','join_test.text'))
#os.path.getatime(path),返回path所指向的文件或者目录的最后存取时间
test_getatime = os.path.getatime("test_from_point_import\\test_point.py")
print(test_getatime)
print(time.ctime(test_getatime))
#os.path.getmtime(path),返回path所指向的文件或者目录的最后修改时间
test_getmtime = os.path.getmtime("test_from_point_import/test_point.py")
print(test_getmtime)
print(time.ctime(test_getmtime))
import sys
#a = sys.argv[0:]#sys.argv 命令行参数list,第一个元素是程序本身路径
#print(a)
#sys.exit(0)#sys.exit(n) 退出程序,正常退出时exit(0)
print(sys.version)#显示Python解释程序的版本信息
print(sys.path)#sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
print(sys.platform)#返回操作系统平台名称
# sys.stdout.write("please:")#这个方法调用的是 ,file 对象中的write方法 ,把字符写到标准输出中,看起来跟print 差不多。
# val = sys.stdin.readline()[:-1]#取不到空格
# for i in range(3):
#     print("hello",' ',val[i])
import shelve#shelve模块是一个简单的k,v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据格式
d = shelve.open("shelve_new_test")
print(d.get("name"))
print(d.get("age"))
print(d.get("job"))
print(d.get("info"))
print(d.get("date"))
# name =["source",'liming']
# age = ['23']
# info = {'stature':168,'addr':'sunshine'}
# d['name'] = name
# d['age'] = age
# d['info'] = info
# job = ['free man']
# d['work'] = job
# d['date'] = datetime.datetime.now()
# d.close()
import xml#实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json更简单。不过,古时候,在json还没诞生的黑暗年代,大家只能选择用xml,至今很多传统公司如金融行业的很多系统接口还是xml
import xml.etree.ElementTree as ET
tree = ET.parse('xmltest')
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,i.attrib)
#只遍历year节点
for node in root.iter("year"):#iter的功能
    print(node.tag,node.text)
#修改
# for node in root.iter("year"):
#     new_year = int(node.text)+1
#     node.text = str(new_year)
#     node.set("updated",'yes')
# tree.write('xmltest')
#删除
for node in root.findall("country"):
    rank = int(node.find('rank').text)
    if rank >7:
        #print("\033[31;1m888\033[0m",node)
        root.remove(node)#这里有一个小问题,是否可以删除符合指定条件的country下的year
tree.write('xmltest')
#创建xml文档
# new_xml = ET.Element("newlist")
# name = ET.SubElement(new_xml,"name",attrib={"enrolled":"yes"})
# age = ET.SubElement(name,"age",attrib={"checked":"no"})
# sex = ET.SubElement(name,'sex')
# sex.text = 'male'
# name2 = ET.SubElement(new_xml,"name",attrib={"enrolled":"yes"})
# age = ET.SubElement(name2,"age",attrib={"checked":"no"})
# age.text = "23"
# name.text = "Source"
# et = ET.ElementTree(new_xml)#生成文档对象
# et.write("new_xml.xml",encoding='utf-8',xml_declaration=True)
# ET.dump(new_xml)#打印生成的格式
import configparser
#使用python生成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'
# topsecret["ForwardX11"] = "no"
# config["DEFAULT"]["ForwardX11"] = 'yes'
# with open("example.ini",'w')as configfile:
#     config.write(configfile)
#读configparser文件
# config = configparser.ConfigParser()
# print(config.sections())
# print(config.read('example.ini'))
# print(config.sections())
# print("DEFAULT"in  config)
# print(config["DEFAULT"]['forwardx11'])
# topsecret = config["topsecret.server.com"]
# print(topsecret['ForwardX11'])
# print(topsecret["host port"])
# for key in config['bitbucket.org']:
#     print(key)#打印出到的为什么是这些东西啊?
# #print(config["bitbucket.org"])
# debug_DEFAULT = config['DEFAULT']
# for key in debug_DEFAULT:
#     print(key,debug_DEFAULT[key])#遍历显示default内容
#configparser增删改查语法
config = configparser.ConfigParser()
config.read('example.ini')
# #############读##############
# secs = config.sections()#eturn a list of section names, excluding [DEFAULT]
# print(secs)
# options = config.options('topsecret.server.com')
# print(options)#可以显示topsecret.server.com下的标题
# item_list = config.items('topsecret.server.com')
# print(item_list)#显示topsecret.server.com下的具体内容
# val = config.get('topsecret.server.com','compression')
# print(val)#可以的到具体的数据
# val2 =config.getint('topsecret.server.com','host port')#只能是整型。
# print(val2)#可以得到具体的整型数据
# #############改写##############
# sec = config.remove_section("topsecret.server.com")#删除了topsecret.server.com
# config.write(open('example.ini','w'))

# sec = config.has_section("source")#确定指定的部分是否存在
# print(sec)
# sec = config.add_section("source")#添加指定的内容
# config.write(open('example.ini','w'))

# config.set('source','age','23')
# config.write(open("example.ini",'w'))

# config.remove_option("source",'age')
# config.write(open('example.ini','w'))

import  hashlib
#hashlib作用:用于加密相关的操作,3.x里代替了md5模块和sha模块,主要提供SHA1,SHA224,SHA384,SHA512,MD5算法
m = hashlib.md5()
m.update(b'Hello')
m.update(b"It's me")
print(m.digest())#Return the digest value as a string of binary data.
m.update(b"It's been a long time since last time we...")
print(m.digest())#2进制格式hash
print(len(m.hexdigest()))#16进制格式hash

# ########MD5########
hash = hashlib.md5()
hash.update(b"administrator")
print(hash.digest())#2进制格式hash
print(hash.hexdigest())#16进制格式hash

# ######### sha512 ##########
hash_sha512 = hashlib.sha512()
hash_sha512.update("吾名大祐哥".encode(encoding='utf-8 '))
print(hash_sha512.hexdigest())

import hmac
#简介:一般用于网络通信中消息加密,前提是双方先要约定好key,就像接头暗号一样,然后消息发送把用key把消息加密,接受方用key+消息明问再加密,
#拿加密后的值跟发送者的相对比是否相等,这样就能验证消息的真实性,及发送者的合法性了。
hmac_test = hmac.new("天王盖地虎".encode("utf-8"),"宝塔镇河妖".encode("utf-8"))
print(hmac_test.hexdigest())

import re
print(re.match("^guo","guojiayouhaha"))#匹配字符开头,若指定flags MUTILINE,这种也可以匹配上(r"^a","\nabc\nee",flags = re.MULTILINE)
print(re.match("g..j.a","guojiayouhaha"))#'.',默认匹配除\n之外的任意一个字符,若指定flag DOTALL,则匹配任意字符,包括换行
print(re.search("foo$","bfoo\nsdfsf",flags=re.MULTILINE).group())#'$',匹配字符结尾,或e.search("foo$","bfoo\nsdfsf",flags = re.MUTILINE).group()也可以
print(re.findall("ab*","cabb3abcbbac"))#'*',匹配*号前的字符0次或多次
print(re.findall("ab+","ab+cd+abb+bba"))#'+',匹配前一个字符1次或多次
print(re.findall('ab?',"abbabdaabbsbab") )#'?',匹配前一个字符1次或0次
print(re.findall("ab{1,2}","ab23abbfgabbb"))#'{n,m},匹配前一个字符n到m次'
print(re.search("abc|ABC","abcdaffafaABC").group())#'|',匹配|左或|右的字符#search可能是检测到一个符合的数据就停止执行了。
print(re.search("(abc){2}a(123|456)c","abcabca456c").group())#分组匹配
print(re.search("\Ahah","Goodhah"))#只从字符开头匹配
print(re.search("hah\Z","Goodhah").group())#匹配字符结尾#还不是很肯定用法
print(re.search("1\d3",'ily123haha').group())#'\d'匹配数字0-9
print(re.search("1\D3",'ily1n3haha0').group())#"\D"匹配非数字
print(re.search("i\wy5\w0","ily520").group())#"\w"匹配[A-Za-z0-9]
print(re.search("i\Wy5\W0","i%y5$0").group())#匹配非[A-Za-z0-9]
print(re.search("\s+","ab\t\rhaha").group())#匹配空白字符,\t,\n,\r
#匹配语法
# re.match()#从头开始匹配
# re.search()#匹配包含
# re.findall()#把所有匹配到的字符放到列表中的元素返回
# re.splitall()#以匹配到的字符当作列表分隔符#似乎在python3里不存在splitall()
# re.sub()#匹配字符并替换
#for example:
print(re.split("n",'i certitude n you love me.'))
print(re.sub("n",'^',"i certitude n you love me "))
#反斜杠的困扰
#与大多数的编程语言相同,正则表达式里使用"\"作为转义字符,这就可能造成反斜杠的困扰。加入你需要匹配文本中的字符"\",那么使用编程
#语言表示的正则表达式里需要4个反斜杠"\\\\",前两个和后两个分别用于在编程语言里转义成反斜杠,转换成两个反斜杠后再在正则表达式里
#转义成一个反斜杠。Python里的原生字符串很好地解决了这个问题,这个例子中的正则表达式可以使用r"\\"表示。同样,匹配一个数字的"\\d"
#可以写成r"\d"。有了原生字符串,你再也不用担心是不是漏写了反斜杠,写出来的表达式也更直观。
print(re.search("\\\\4","fuck\\4hah"))#不晓得为什么不行
#re.I(re.IGNORECASE)#忽略大小写(括号内的是完整写法,下同)
#M(MULTILINE)#多行模式,改变"^"和"$"的行为
#S(DOTALL):点任意匹配模式,改变"."的行为
print(re.search("TEST","test",re.I))#re.I忽略大小写
print(re.sub(r"^a",'_',"\nabc\naee",flags = re.MULTILINE))#'^'与"$"默认匹配整个字符串的开头和结尾re.MULTILINE可以改变它的行为,换行之后依旧可以进行匹配
print(re.search('.ha','any\rhaha\n',flags=re.S))#改变点匹配模式,\r\t\n也可以匹配的到。

  

猜你喜欢

转载自www.cnblogs.com/source12/p/9927204.html
今日推荐