hashlib模块:加密

import hashlib
# 基本使用
cipher = hashlib.md5('需要加密的数据的二进制形式'.encode('utf-8'))
print(cipher.hexdigest()) # 加密结果码 # 加盐
cipher = hashlib.md5()
cipher.update('前盐'.encode('utf-8'))
cipher.update('需要加密的数据'.encode('utf-8'))
cipher.update('后盐'.encode('utf-8'))
print(cipher.hexdigest()) # 加密结果码 # 其他算法
cipher = hashlib.sha3_256(b'')
print(cipher.hexdigest())
cipher = hashlib.sha3_512(b'')
print(cipher.hexdigest())

import hashlib

m=hashlib.md5()# m=hashlib.sha256()

m.update('hello'.encode('utf8'))
print(m.hexdigest()) #5d41402abc4b2a76b9719d911017c592

m.update('alvin'.encode('utf8'))

print(m.hexdigest()) #92a7e713c30abbb0319fa07da2a5c4af

m2=hashlib.md5()
m2.update('helloalvin'.encode('utf8'))
print(m2.hexdigest()) #92a7e713c30abbb0319fa07da2a5c4af

'''
注意:把一段很长的数据update多次,与一次update这段长数据,得到的结果一样
但是update多次为校验大文件提供了可能。
'''

hmac  模块

python 还有一个 hmac 模块,它内部对我们创建 key 和 内容 进行进一步的处理然后再加密:

1 import hmac
2 h = hmac.new('alvin'.encode('utf8'))
3 h.update('hello'.encode('utf8'))
4 print (h.hexdigest())#320df9832eab4c038b6c1d7ed73a5940
# 必须加盐
cipher = hmac.new('盐'.encode('utf-8'))
cipher.update('数据'.encode('utf-8'))
print(cipher.hexdigest()) #要想保证hmac最终结果一致,必须保证:
#1:hmac.new括号内指定的初始key一样
#2:无论update多少次,校验的内容累加到一起是一样的内容 import hmac h1=hmac.new(b'egon')
h1.update(b'hello')
h1.update(b'world')
print(h1.hexdigest()) h2=hmac.new(b'egon')
h2.update(b'helloworld')
print(h2.hexdigest()) h3=hmac.new(b'egonhelloworld')
print(h3.hexdigest()) '''
f1bf38d054691688f89dcd34ac3c27f2
f1bf38d054691688f89dcd34ac3c27f2
bcca84edd9eeb86f30539922b28f3981
'''

configparser模块

# 注释1
; 注释2 [section1]
k1 = v1
k2:v2
user=egon
age=18
is_admin=true
salary=31 [section2]
k1 = v1

读取

import configparser

config=configparser.ConfigParser()
config.read('a.cfg') #查看所有的标题
res=config.sections() #['section1', 'section2']
print(res) #查看标题section1下所有key=value的key
options=config.options('section1')
print(options) #['k1', 'k2', 'user', 'age', 'is_admin', 'salary'] #查看标题section1下所有key=value的(key,value)格式
item_list=config.items('section1')
print(item_list) #[('k1', 'v1'), ('k2', 'v2'), ('user', 'egon'), ('age', '18'), ('is_admin', 'true'), ('salary', '31')] #查看标题section1下user的值=>字符串格式
val=config.get('section1','user')
print(val) #egon #查看标题section1下age的值=>整数格式
val1=config.getint('section1','age')
print(val1) # #查看标题section1下is_admin的值=>布尔值格式
val2=config.getboolean('section1','is_admin')
print(val2) #True #查看标题section1下salary的值=>浮点型格式
val3=config.getfloat('section1','salary')
print(val3) #31.0

改写

import configparser

config=configparser.ConfigParser()
config.read('a.cfg',encoding='utf-8') #删除整个标题section2
config.remove_section('section2') #删除标题section1下的某个k1和k2
config.remove_option('section1','k1')
config.remove_option('section1','k2') #判断是否存在某个标题
print(config.has_section('section1')) #判断标题section1下是否有user
print(config.has_option('section1','')) #添加一个标题
config.add_section('egon') #在标题egon下添加name=egon,age=18的配置
config.set('egon','name','egon')
config.set('egon','age',18) #报错,必须是字符串 #最后将修改的内容写入文件,完成最终的修改
config.write(open('a.cfg','w'))
import configparser

config = configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval': '',
'Compression': 'yes',
'CompressionLevel': ''} config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '' # mutates the parser
topsecret['ForwardX11'] = 'no' # same here
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini', 'w') as configfile:
config.write(configfile) 基于上述方法添加一个ini文档

添加ini

 suprocess模块

import  subprocess

'''
sh-3.2# ls /Users/egon/Desktop |grep txt$
mysql.txt
tt.txt
事物.txt
''' res1=subprocess.Popen('ls /Users/jieli/Desktop',shell=True,stdout=subprocess.PIPE)
res=subprocess.Popen('grep txt$',shell=True,stdin=res1.stdout,
stdout=subprocess.PIPE) print(res.stdout.read().decode('utf-8')) #等同于上面,但是上面的优势在于,一个数据流可以和另外一个数据流交互,可以通过爬虫得到结果然后交给grep
res1=subprocess.Popen('ls /Users/jieli/Desktop |grep txt$',shell=True,stdout=subprocess.PIPE)
print(res1.stdout.read().decode('utf-8')) #windows下:
# dir | findstr 'test*'
# dir | findstr 'txt$'
import subprocess
res1=subprocess.Popen(r'dir C:\Users\Administrator\PycharmProjects\test\函数备课',shell=True,stdout=subprocess.PIPE)
res=subprocess.Popen('findstr test*',shell=True,stdin=res1.stdout,
stdout=subprocess.PIPE) print(res.stdout.read().decode('gbk')) #subprocess使用当前系统默认编码,得到结果为bytes类型,在windows下需要用gbk解码

xlrd模块:excel读

            年终报表
教学部 市场部 咨询部 总计
Jan-19 10 15 5 30
Feb-19 10 15 5 30
Mar-19 10 15 5 30
Apr-19 10 15 5 30
May-19 10 15 5 30
Jun-19 10 15 5 30
Jul-19 10 15 5 30
Aug-19 10 15 5 30
Sep-19 10 15 5 30
Oct-19 10 15 5 30
Nov-19 10 15 5 30
Dec-19 10 15 5 30 import xlrd
# 读取文件
work_book = xlrd.open_workbook("机密数据.xlsx")
# 获取所有所有表格名称
print(work_book.sheet_names())
# 选取一个表
sheet = work_book.sheet_by_index(1)
# 表格名称
print(sheet.name)
# 行数
print(sheet.nrows)
# 列数
print(sheet.ncols)
# 某行全部
print(sheet.row(6))
# 某列全部
print(sheet.col(6))
# 某行列区间
print(sheet.row_slice(6, start_colx=0, end_colx=4))
# 某列行区间
print(sheet.col_slice(3, start_colx=3, end_colx=6))
# 某行类型 | 值
print(sheet.row_types(6), sheet.row_values(6))
# 单元格
print(sheet.cell(6,0).value) # 取值
print(sheet.cell(6,0).ctype) # 取类型
print(sheet.cell_value(6,0)) # 直接取值
print(sheet.row(6)[0])
# 时间格式转换
print(xlrd.xldate_as_datetime(sheet.cell(6, 0).value, 0))

xlwt模块:excel写

import xlwt
# 创建工作簿
work = xlwt.Workbook()
# 创建一个表
sheet = work.add_sheet("员工信息数据")
# 创建一个字体对象
font = xlwt.Font()
font.name = "Times New Roman" # 字体名称
font.bold = True # 加粗
font.italic = True # 斜体
font.underline = True # 下划线
# 创建一个样式对象
style = xlwt.XFStyle()
style.font = font
keys = ['Owen', 'Zero', 'Egon', 'Liuxx', 'Yhh']
# 写入标题
for k in keys:
sheet.write(0, keys.index(k), k, style)
# 写入数据
sheet.write(1, 0, 'cool', style)
# 保存至文件
work.save("test.xls")

 复习模块

# import datetime

# print(datetime.datetime.now())
# print(datetime.datetime.now()+datetime.timedelta(days=3))
# print(datetime.datetime.now()+datetime.timedelta(seconds=111)) # 2019-04-20 20:00:45.964735
# 2019-04-23 20:00:45.964735
# 2019-04-20 20:02:36.964735 # current_time=datetime.datetime.now()
# print(current_time.replace(year=1977))
# 1977-04-20 20:02:01.534058 # print(datetime.date.fromtimestamp(11111111))
# 时间戳直接转成日期格式 1970-05-09 # 打印进度条 # print('[%-50s]' %'#')
# print('[%-50s]' %'##')
# print('[%-50s]' %'###')
# [# ]
# [## ]
# [### ] # num=30
# print('%s%%'%num)
# 30% 第一个%是取消第二个%的特殊意义的 # width=30
# print(('[%%-%ds]'%width)%'#')
# print(('[%%-%ds]'%width)%'##')
# print(('[%%-%ds]'%width)%'###')
# [%-(width)s] %#
# [# ]
# [## ]
# [### ] # def progress(percent,width=50):
# if percent>1:
# percent=1
# show_str=('[%%-%ds]'%width) %(int(width*percent)*'#')
# print('\r%s %d%%'%(show_str,int(100*percent)),end='')
#
# import time
# recv_size=0
# total_size=8097
# while recv_size<total_size:
# time.sleep(0.1)
# recv_size+=576
# percent=recv_size/total_size
# progress(percent) # import shutil
# import time
# ret=shutil.make_archive(
# 'E:\代码存放位置\第五周%s'%time.strftime('%Y-%m-%d'),
# 'gztar',
# root_dir=r'E:\代码存放位置\第五周\继承.py'
# ) # import shelve
# info1={'age':18,'height':180,'weight':80}
# info2={'age':73,'height':160,'weight':80}
#
# d=shelve.open('db.shv')
# d['egon']=info1
# d['alex']=info1
# d.close() # d=shelve.open('db.shv')
# print(d['egon'])
# print(d['alex'])
# d.close()
# {'age': 18, 'height': 180, 'weight': 80}
# {'age': 18, 'height': 180, 'weight': 80} #
# d=shelve.open('db.shv',writeback=True)
# d['alex']['age']=1000
# print(d['alex'])
# d.close()
# {'age': 1000, 'height': 180, 'weight': 80} # d=shelve.open('db.shv')
# print(d['alex'])
# d.close()
# {'age': 1000, 'height': 180, 'weight': 80} # ==========================================查
# import xml.etree.cElementTree as ET
#
# tree=ET.parse('a.xml')
# root=tree.getroot()
# print(root.tag)
# data
# 三种查找节点的方式
# res=root.iter('rank') #会在整个树中进行查找,而且是查找到所有
# for item in res:
# print(item)
# print('='*50)
# print(item.tag) #标签名
# print(item.attrib) #属性
# print(item.text) #文本内容
# == == == == == == == == == == == == == == == == == == == == == == == == ==
# rank
# {'updated': 'yes'}
#
# == == == == == == == == == == == == == == == == == == == == == == == == ==
# rank
# {'updated': 'yes'}
#
# == == == == == == == == == == == == == == == == == == == == == == == == ==
# rank
# {'updated': 'yes'}
# # res=root.find('country') #只能在当前元素的下一级开始查找,并且只找到一个就结束
# print(res.tag)
# print(res.attrib)
# print(res.text)
# country
# {'name': 'Liechtenstein'}
# nb=res.find('neighbor') #在当前country的节点往下查找 找到只找到一个就结束
# print(nb.attrib)
# {'name': 'Austria', 'direction': 'E'} # cy=root.findall('country') #只能在当前元素的下一级开始查找
# print([item.attrib for item in cy])
# [{'name': 'Liechtenstein'}, {'name': 'Singapore'}, {'name': 'Panama'}] # # -=====================================改
# import xml.etree.ElementTree as ET
# tree=ET.parse('a.xml')
# root=tree.getroot()
#
# for year in root.iter('year'): #会在整个树中进行查找,而且是查找所有的
# year.text=str(int(year.text)+10)
# year.attrib={'updated':'yes'}
#
# tree.write('b.xml')
# tree.write('a.xml') # -=====================================增
# import xml.etree.ElementTree as ET
# tree=ET.parse('a.xml')
# root=tree.getroot()
#
# for country in root.iter('country'):
# # print(country)
# year=country.find('year')
# # print(year)
# if int(year.text)>2000:
# # print(country.attrib)
# ele=ET.Element('egon')
# ele.attrib={'nb':'yes'}
# ele.text='非常帅'
# country.append(ele)
# # country.remove(year)
# tree.write('b.xml') # import os
# while True:
# cmd=input('>>>: ').strip()
# if not cmd:continue
# # print('%s run'%cmd)
# res=os.system(cmd) #dir # network.send(res) # import subprocess #运行系统命令 允许控制命令的结果是打印到屏幕上还是做其他的事情
# obj=subprocess.Popen('dir', #正确命令
# shell=True, #命令解释器
# stdout=subprocess.PIPE, #正确管道
# stderr=subprocess.PIPE #错误管道
# )
#
# res1=obj.stdout.read()
# print('正确结果111: ',res1.decode('gbk'))
#
# res2=obj.stdout.read()
# print('正确结果222: ',res2.decode('gbk')) #只能取走一次,取走了正确管道里就没有信息了
# #
# res2=obj.stderr.read() #只解读命令
# print('错误结果: ',res2.decode('gbk'))
# import configparser #解析配置 ini这种格式文件里面的组成形式
config=configparser.ConfigParser()
config.read('my.ini') # secs=config.sections() #标题
# print(secs)
# ['egon', 'lqz'] # print(config.options('egon'))
# ['age', 'pwd', 'sex', 'salary', 'is_beautiful'] # age=config.get('egon','age')
# print(age,type(age)) #18 <class 'str'>
# age=config.getint('egon','age')
# print(age,type(age)) #18 <class 'int'> # salary=config.getfloat('egon','salary')
# print(salary,type(salary)) #5.1 <class 'float'> b=config.getboolean('egon','is_beautiful')
print(b,type(b)) #True <class 'bool'>

复习 模块

hashlib hmac configparser subprocess xlrd xlwt的更多相关文章

  1. 20 常用模块 hashlib hmac:加密 xml xlrd xlwt:excel读|写 configparser subprocess

    hashlib模块:加密 加密: 1.有解密的加密方式 2.无解密的加密方式:碰撞检查 hashlib -- 1)不同数据加密后的结果一定不一致 -- 2)相同数据的加密结果一定是一致的 import ...

  2. configparser模块,subprocess 模块,xlrd,xlwt ,xml 模块,面向对象

    1. configparser模块 2.subprocess 模块 3.xlrd,xlwt 4.xml 模块 5.面向对象 面向对象是什么? 是一种编程思想,指导你如何更好的编写代码 关注点在对象 具 ...

  3. Python(文件、文件夹压缩处理模块,shelve持久化模块,xml处理模块、ConfigParser文档配置模块、hashlib加密模块,subprocess系统交互模块 log模块)

    OS模块 提供对操作系统进行调用的接口 os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径 os.chdir("dirname")  改变当前脚本工作目 ...

  4. [xml模块、hashlib模块、subprocess模块、os与sys模块、configparser模块]

    [xml模块.hashlib模块.subprocess模块.os与sys模块.configparser模块] xml模块 XML:全称 可扩展标记语言,为了能够在不同的平台间继续数据的交换,使交换的数 ...

  5. 使用Python对Excel表格进行简单的读写操作(xlrd/xlwt)

    算是一个小技巧吧,只是进行一些简单的读写操作.让人不爽的是xlrd和xlwt是相对独立的,两个模块的对象不能通用,读写无法连贯操作,只能单独读.单独写,尚不知道如何解决. #①xlrd(读) #cod ...

  6. Python操作Excel——win32com模块和xlrd+xlwt+xlutils组合

    今天,接到一个任务,要生成大约两百个excel文件,从2006年到2013年,每个月两个文件,这些文件中除了几个关于日期的单元格不同外,其他数据都相同,所以就想到可以用python写一个小脚本,自动生 ...

  7. python读写Excel文件的函数--使用xlrd/xlwt

    python中读取Excel的模块或者说工具有很多,如以下几种: Packages 文档下载 说明 openpyxl Download | Documentation | Bitbucket  The ...

  8. 自己总结python用xlrd\xlwt读写excel

    1.首先安装xlrd\xlwt模块 xlrd模块下载地址: https://pypi.python.org/pypi/xlrd xlwt模块下载地址: https://pypi.python.org/ ...

  9. 【Python】 hash值计算 hashlib & hmac

    hashlib & hmac *不是很清楚能不能把这种hash值取样算法称之为加密,但是似乎好像也是这么说的哈(非科班出身的野路子就是没这种基本知识的) ■ 基本用法 hashlib支持MD5 ...

随机推荐

  1. javascript的数组之splice()

    splice()方法通过删除现有元素和/或添加新元素来更改一个数组的内容.修改数组自身 var months = ['Jan', 'March', 'April', 'June']; months.s ...

  2. js图片预加载与延迟加载

    图片预加载的机制原理:就是提前加载出图片来,给前端的服务器有一定的压力. 图片延迟加载的原理:为了缓解前端服务器的压力,延缓加载图片,符合条件的时候再加载图片,当然不符合的条件就不加载图片.​ 预加载 ...

  3. [dev] 刷HHKP的一般流程及常见错误(多图慎点)

    ( 为什么打了个dev的tag?development不用键盘,难道用鼠标??) 嗯呐,我有个HHKP,你看: 好不好看? 脏不脏? 接下来讲一下,我是怎么刷它,要看完哝,不然拆坏了不要怪我. 本来我 ...

  4. 红黑树与AVL特性

    红黑树:比较平衡的二叉树,没有一条路径会比其他路径长2倍,因而是近似平衡的.所以相对于严格要求平衡的AVL树来说,它的旋转保持平衡次数较少.插入删除次数多的情况下我们就用红黑树来取代AVL. 红黑树规 ...

  5. python练习题-day26

    #bim(property) class People: def __init__(self,name,weight,height): self.name=name self.weight=weigh ...

  6. 理解 JavaScript 中的 this

    前言 理解this是我们要深入理解 JavaScript 中必不可少的一个步骤,同时只有理解了 this,你才能更加清晰地写出与自己预期一致的 JavaScript 代码. 本文是这系列的第三篇,往期 ...

  7. ThinkPHP安全规范指引

    流年 发布于 ThinkPHP官方博客: https://blog.thinkphp.cn/789333 本文主要和大家探讨一下ThinkPHP的安全注意事项,可以作为ThinkPHP建议的安全规范实 ...

  8. [TJOI2009]猜数字

    题目描述 现有两组数字,每组k个,第一组中的数字分别为:a1,a2,...,ak表示,第二组中的数字分别用b1,b2,...,bk表示.其中第二组中的数字是两两互素的.求最小的非负整数n,满足对于任意 ...

  9. CarbonData-1:common

    最近公司需要对CarbonData进一步应用,或许封装进产品,或许是为了解析CarbonData元数据,于是开始预研CarbonData,下面将保持每天一篇以上的阅读CarbonData源码博客,由于 ...

  10. 构建RN或Weex项目时,使用Android Studio常遇到的问题

    1 . androidStudio报错No cached version available for offline mode 解决方法 原因是之前为了提高编译速度,在Gradle设置选项中开启了Of ...