标签:包含 内容 重要 分割文件 rand 等等 tag 完全 int
内置模块自定义模块第三方模块
import random
print(random.random()) # 随机显示大于0且小于1之间的某个小数
print(random.randint(1, 3)) # 随机显示一个大于等于1且小于等于3之间的整数
print(random.randrange(1, 3)) # 随机显示一个大于等于1且小于3之间的整数
print(random.choice([1, ‘23‘, [4, 5]])) # 随机选择列表中的元素,1或者23或者[4,5]
print(random.sample([1, ‘23‘, [4, 5]], 2)) # 随机选择列表元素任意2个组合,拼成一个新的列表
print(random.uniform(1, 3)) # 随机选择大于1小于3的小数,如1.927109612082716
item = [1, 3, 5, 7, 9]
random.shuffle(item) # 打乱item的顺序,相当于"洗牌"
print(item)
运行结果#->
0.8411519662343422
2
1
1
[[4, 5], ‘23‘]
1.1835899789185504
[9, 7, 1, 3, 5]
import random
def v_code(n=5):
res=‘‘
for i in range(n):
num=random.randint(0,9) # 随机选择数字
s=chr(random.randint(65,90)) # 随机选择字母,chr()转换数字为ASCII码对应的字母
add=random.choice([num,s])
res+=str(add) #res = res + str(add) 字符串拼接
return res
print(v_code(4))
运行结果:
91W2
import time
#我们先以当前时间为准,快速认识三种形式的时间print(time.time()) # 时间戳:1487130156.419527,计算机用的时间
print(time.strftime("%Y-%m-%d %X")) #格式化的时间字符串:‘2017-02-15 11:40:53‘
print(time.localtime()) #本地时区的struct_time,结构化的时间
print(time.gmtime()) #UTC时区的struct_time,标准时间
运行结果:
1496747605.4952035
2017-06-06 19:13:25
time.struct_time(tm_year=2017, tm_mon=6, tm_mday=6, tm_hour=19, tm_min=13, tm_sec=25, tm_wday=1, tm_yday=157, tm_isdst=0)
time.struct_time(tm_year=2017, tm_mon=6, tm_mday=6, tm_hour=11, tm_min=13, tm_sec=25, tm_wday=1, tm_yday=157, tm_isdst=0)
print(time.localtime(time.time())) #将当前时间戳转换成结构化的时间
#->time.struct_time(tm_year=2017, tm_mon=6, tm_mday=6, tm_hour=21, tm_min=0, tm_sec=25, tm_wday=1, tm_yday=157, tm_isdst=0)
print(time.mktime(time.localtime())) #将当前的结构化时间转换为时间戳格式的时间
#->1496754025.0
print(time.strftime(‘%Y-%m-%d %X‘, time.localtime())) #将当前的结构化的时间转换为格式化的字符串时间
#->2017-06-06 21:00:25
print(time.strptime(‘2017-06-06 11:59:59‘, ‘%Y-%m-%d %X‘)) #将字符串时间转换为结构化的时间
#->time.struct_time(tm_year=2017, tm_mon=6, tm_mday=6, tm_hour=11, tm_min=59, tm_sec=59, tm_wday=1, tm_yday=157, tm_isdst=-1)
print(time.ctime(time.time())) #将当前时间戳转换成linux形式的时间格式
#->Tue Jun 6 21:07:21 2017
print(time.asctime(time.localtime())) #将当前结构化的时间转换为linux形式的时间格式
#->Tue Jun 6 21:07:21 2017
print(time.asctime())
print(time.strftime(‘%a %b %d %H:%M:%S %Y‘, time.localtime()))
运行结果#->
Tue Jun 6 21:04:54 2017
Tue Jun 06 21:04:54 2017
os.path.normcase(‘c:/windows\\system32\\‘)
#-> ‘c:\\windows\\system32\\‘
os.path.normpath(‘c://windows\\System32\\../Temp/‘)
#-> ‘c:\\windows\\Temp‘
a=‘/Users/jieli/test1/\\\a1/\\\\aa.py/../..‘
print(os.path.normpath(a))
#-> /Users/jieli/test1
os路径处理
#方式一:推荐使用
import os
#具体应用
import os,sys
possible_topdir = os.path.normpath(os.path.join(
os.path.abspath(__file__),
os.pardir, #上一级
os.pardir,
os.pardir
))
sys.path.insert(0,possible_topdir)
#方式二:不推荐使用
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
#文件:argv.py
#!/usr/bin/enc python
#
import sys
print(sys.argv) #显示文件所在绝对路径,为列表的第0个元素
print(sys.argv[1]) #以空格为分隔符,将后面的字符串生成一个列表,显示列表第一个元素
print(sys.argv[2]) #显示第二个元素
#->在命令行终端执行:
>python F:\oldboy_python\objects\day06\练习\tmp.py --host 192.168.1.1 --port 8080
[‘F:\\oldboy_python\\objects\\day06\\\xc1\xb7\xcf\xb0\\tmp.py‘, ‘--host‘, ‘192.168.1.1‘, ‘--port‘, ‘8080‘]
--host
192.168.1.1
import sys, time
for i in range(100):
sys.stdout.write(‘%s\r‘, %(‘#‘*i))
sys.stdout.flush()
time.sleep(0.1)
import shutil
shutil.copyfileobj(open(‘old_file‘, ‘r‘), open(‘new_file‘, ‘w‘))
import shutil
shutil.copytree(‘folder1‘, ‘folder2‘, ignore=shutil.ignore_patterns(‘*.pyc‘, ‘tmp*‘))
# 递归拷贝folder1中的所有目录和文件,排除‘*.pyc‘, ‘tmp*‘文件,folder2事前不能存在,且对folder2的父目录有可写权限
--base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
-->如 data_bak=>保存至当前路径
-->如:/tmp/data_bak =>保存至/tmp/
--format:压缩包种类,“zip”, “tar”, “bztar”,“gztar”
--root_dir:要压缩的文件夹路径(默认当前目录)
--owner:用户,默认当前用户
--group:组,默认当前组
#将 /data 下的文件打包放置当前程序目录
import shutil
ret = shutil.make_archive("data_bak", ‘gztar‘, root_dir=‘/data‘)
#将 /data下的文件打包放置 /tmp/目录
import shutil
ret = shutil.make_archive("/tmp/data_bak", ‘gztar‘, root_dir=‘/data‘)
import zipfile
# 压缩
z = zipfile.ZipFile(‘laxi.zip‘, ‘w‘)
z.write(‘a.log‘)
z.write(‘data.data‘)
z.close()
# 解压
z = zipfile.ZipFile(‘laxi.zip‘, ‘r‘)
z.extractall(path=‘.‘)
z.close()
import tarfile
# 压缩
>>> t=tarfile.open(‘/tmp/egon.tar‘,‘w‘)
>>> t.add(‘/test1/a.py‘,arcname=‘a.bak‘)
>>> t.add(‘/test1/b.py‘,arcname=‘b.bak‘)
>>> t.close()
# 解压
>>> t=tarfile.open(‘/tmp/egon.tar‘,‘r‘)
>>> t.extractall(‘/egon‘)
>>> t.close()
import json
x="[null,true,false,1]"
print(eval(x))
print(json.loads(x))
运行结果:
print(eval(x)) #报错,无法解析null类型,而json就可以
File "<string>", line 1, in <module>
NameError: name ‘null‘ is not defined
import json
x="[null,true,false,1]"
print(json.loads(x))
运行结果:
[None, True, False, 1]
import json
dic = {
‘name‘: ‘alex‘,
‘age‘: 9000,
‘height‘: ‘180cm‘
}
res = json.dumps(dic) #编码,把一个python对象编码转换成json字符串
print(res,type(res))
with open(‘a.json‘, ‘w‘) as f:
f.write(res)
运行结果:
{"name": "alex", "age": 9000, "height": "180cm"} <class ‘str‘>
写入文件a.json,内容为{"name": "alex", "age": 9000, "height": "180cm"}
with open(‘a.json‘, ‘r‘) as f:
dic = json.loads(f.read())
print(dic, type(dic))
运行结果:
{‘age‘: 9000, ‘height‘: ‘180cm‘, ‘name‘: ‘alex‘} <class ‘dict‘>
import json
json.dump(dic, open(‘b.json‘,‘w‘)) #序列化
res = json.load(open(‘b.json‘, ‘r‘)) #反序列化
print(res, type(res))
#->序列化结果:
生成新的文件b.json,内容为:{"name": "alex", "age": 9000, "height": "180cm"}
#->反序列化结果:
{‘name‘: ‘alex‘, ‘age‘: 9000, ‘height‘: ‘180cm‘} <class ‘dict‘>
import pickle
dic = {
‘name‘: ‘alex‘,
‘age‘: 9000,
‘height‘: ‘180cm‘
}
print(pickle.dumps(dic))
#->运行结果:
b‘\x80\x03}q\x00(X\x04\x00\x00\x00nameq\x01X\x04\x00\x00\x00alexq\x02X\x03\x00\x00\x00ageq\x03M(#X\x06\x00\x00\x00heightq\x04X\x05\x00\x00\x00180cmq\x05u.‘
import pickle
dic = {
‘name‘: ‘alex‘,
‘age‘: 9000,
‘height‘: ‘180cm‘
}
with open(‘a.pickle‘, ‘wb‘) as f:
f.write(pickle.dumps(dic))
with open(‘a.pickle‘, ‘rb‘) as f:
a = pickle.loads(f.read())
print(a, type(a))
import pickle
pickle.dump(dic, open(‘b.pickle‘, ‘wb‘))
res = pickle.load(open(‘b.pickle‘, ‘rb‘))
print(res, type(res))
import json,pickle
def func():
print(‘from func...‘)
json.dumps(func)
#->
运行结果:#TypeError: <function func at 0x0000000000B7E1E0> is not JSON serializable
f = pickle.dumps(func)
print(f)
pickle.dump(func, open(‘c.pkl‘, ‘wb‘))
res = pickle.load(open(‘c.pkl‘, ‘rb‘))
print(res)
res()
#->运行结果:
b‘\x80\x03c__main__\nfunc\nq\x00.‘
<function func at 0x0000000000D9E1E0>
from func...
import shelve
f=shelve.open(r‘sheve.txt‘)
f[‘stu1_info‘]={‘name‘:‘egon‘,‘age‘:18,‘hobby‘:[‘piao‘,‘smoking‘,‘drinking‘]}
f[‘stu2_info‘]={‘name‘:‘gangdan‘,‘age‘:53}
f[‘school_info‘]={‘website‘:‘http://www.pypy.org‘,‘city‘:‘beijing‘}
print(f[‘stu1_info‘][‘hobby‘])
f.close()
#->
会生成3个文件:sheve.txt.bak,sheve.txt.dat,sheve.txt.dir
[‘piao‘, ‘smoking‘, ‘drinking‘]
logging.basicConfig(
format=‘%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s‘,
datefmt=‘%Y-%m-%d %H:%M:%S %p‘,
level=10)
logging.debug(‘debug‘)
logging.info(‘info‘)
logging.warning(‘warning‘)
logging.error(‘error‘)
logging.critical(‘critical‘)
logging.log(10,‘log‘)
#如果level=40,则只有logging.critical和loggin.error的日志会被打印
#->
2017-06-07 22:57:16 PM - root - DEBUG -tmp: debug
2017-06-07 22:57:16 PM - root - INFO -tmp: info
2017-06-07 22:57:16 PM - root - WARNING -tmp: warning
2017-06-07 22:57:16 PM - root - ERROR -tmp: error
2017-06-07 22:57:16 PM - root - CRITICAL -tmp: critical
# logging.conf
[loggers]
keys=root
[logger_root]
level=DEBUG
handlers=consoleHandler
#,timedRotateFileHandler,errorTimedRotateFileHandler
#################################################
[handlers]
keys=consoleHandler,timedRotateFileHandler,errorTimedRotateFileHandler
[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)
[handler_timedRotateFileHandler]
class=handlers.TimedRotatingFileHandler
level=DEBUG
formatter=simpleFormatter
args=(‘debug.log‘, ‘H‘)
[handler_errorTimedRotateFileHandler]
class=handlers.TimedRotatingFileHandler
level=WARN
formatter=simpleFormatter
args=(‘error.log‘, ‘H‘)
#################################################
[formatters]
keys=simpleFormatter, multiLineFormatter
[formatter_simpleFormatter]
format= %(levelname)s %(threadName)s %(asctime)s: %(message)s
datefmt=%H:%M:%S
[formatter_multiLineFormatter]
format= ------------------------- %(levelname)s -------------------------
Time: %(asctime)s
Thread: %(threadName)s
File: %(filename)s(line %(lineno)d)
Message:
%(message)s
datefmt=%Y-%m-%d %H:%M:%S
import os
filepath = os.path.join(os.path.dirname(__file__), ‘logging.conf‘)
logging.config.fileConfig(filepath)
return logging.getLogger()
import logging
logging.basicConfig(level=logging.DEBUG)
fmt = ‘%(levelname)s:%(message)s‘
console_handler = logging.StreamHandler()
console_handler.setFormatter(logging.Formatter(fmt))
logging.getLogger().addHandler(console_handler)
logging.info(‘hello!‘)
# INFO:root:hello!
# INFO:hello!
import logging
def get_logger():
fmt = ‘%(levelname)s:%(message)s‘
console_handler = logging.StreamHandler()
console_handler.setFormatter(logging.Formatter(fmt))
logger = logging.getLogger(‘App‘)
logger.setLevel(logging.INFO)
logger.addHandler(console_handler)
return logger
def call_me():
logger = get_logger()
logger.info(‘hi‘)
call_me()
call_me()
# INFO:hi
# INFO:hi
# INFO:hi
import logging
def get_logger():
fmt = ‘%(levelname)s: %(message)s‘
console_handler = logging.StreamHandler()
console_handler.setFormatter(logging.Formatter(fmt))
logger = logging.getLogger(‘App‘)
logger.setLevel(logging.INFO)
logger.addHandler(console_handler)
return logger
def foo():
logging.basicConfig(format=‘[%(name)s]: %(message)s‘)
logging.warn(‘some module use root logger‘)
def main():
logger = get_logger()
logger.info(‘App start.‘)
foo()
logger.info(‘App shutdown.‘)
main()
# INFO: App start.
# [root]: some module use root logger
# INFO: App shutdown.
# [App]: App shutdown.
p = subprocess.Popen(‘dir‘, shell=True)
#->
列出的就是文件当前目录内容
res=subprocess.Popen("dir", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(res)
print(res.stdout.read())
print(res.stdout.read().decode(‘gbk‘))
<subprocess.Popen object at 0x000000000067D438> #res
b‘ \xc7\xfd\xb6\xaf\xc6\xf7 F \xd....
#res.stdout.read()驱动器 F 中的卷是 Bak
#res.stdout.read().decode(‘gbk‘),此处的gbk编码格式为当前系统编码格式卷的序列号是 AC2A-165F
F:\oldboy_python\objects\day06\练习 的目录
...
res=subprocess.Popen("dir456", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(res)
print(res.stderr.read().decode(‘gbk‘))
#->
<subprocess.Popen object at 0x0000000000A1AA90>
‘dir456‘ 不是内部或外部命令,也不是可运行的程序
或批处理文件。
#模拟 dir |grep txt$
res1=subprocess.Popen(r‘dir E:\wupeiqi\s17\day06‘,shell=True,stdout=subprocess.PIPE)
res=subprocess.Popen(r‘findstr txt*‘,shell=True,
stdin=res1.stdout,stderr=subprocess.PIPE,stdout=subprocess.PIPE)# 注释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) #18
#查看标题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‘)
#删除整个标题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‘))
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
[bitbucket.org]
User = hg
[topsecret.server.com]
Port = 50022
ForwardX11 = no
import configparser
config=configparser.ConfigParser()
config.read(‘test.ini‘,encoding=‘utf-8‘)
res=config.sections()
print(res)
‘‘‘
打印结果:
[‘bitbucket.org‘, ‘topsecret.server.com‘]
‘‘‘
import configparser
config=configparser.ConfigParser()
config.read(‘test.ini‘,encoding=‘utf-8‘)
res=config.items(‘bitbucket.org‘)
print(res)
‘‘‘
打印结果:(包含DEFAULT以及bitbucket.org这俩标题下所有的items)
[(‘serveraliveinterval‘, ‘45‘), (‘compression‘, ‘yes‘), (‘compressionlevel‘, ‘9‘), (‘forwardx11‘, ‘yes‘), (‘user‘, ‘hg‘)]
‘‘‘
import configparser
config=configparser.ConfigParser()
config.read(‘test.ini‘,encoding=‘utf-8‘)
res=config.options(‘bitbucket.org‘)
print(res)
‘‘‘
打印结果:(包含DEFAULT以及bitbucket.org这俩标题下所有的键)
[‘user‘, ‘serveraliveinterval‘, ‘compression‘, ‘compressionlevel‘, ‘forwardx11‘]‘‘‘
import configparser
config=configparser.ConfigParser()
config.read(‘test.ini‘,encoding=‘utf-8‘)
res1=config.get(‘bitbucket.org‘,‘user‘)
res2=config.getint(‘topsecret.server.com‘,‘port‘)
res3=config.getfloat(‘topsecret.server.com‘,‘port‘)
res4=config.getboolean(‘topsecret.server.com‘,‘ForwardX11‘)
print(res1)
print(res2)
print(res3)
print(res4)
‘‘‘
打印结果:
hg
50022.0
False
‘‘‘
import configparser
config=configparser.ConfigParser()
config.read(‘test.ini‘,encoding=‘utf-8‘)
#检查
has_sec=config.has_section(‘bitbucket.org‘)
print(has_sec) #打印True
#添加节点
config.add_section(‘egon‘) #已经存在则报错
config[‘egon‘][‘username‘]=‘gangdan‘
config[‘egon‘][‘age‘]=‘18‘
config.write(open(‘test.ini‘,‘w‘))
#删除节点
config.remove_section(‘egon‘)
config.write(open(‘test.ini‘,‘w‘))
import configparser
config=configparser.ConfigParser()
config.read(‘test.ini‘,encoding=‘utf-8‘)
#检查
has_sec=config.has_option(‘bitbucket.org‘,‘user‘) #bitbucket.org下有一个键user
print(has_sec) #打印True
#删除
config.remove_option(‘DEFAULT‘,‘forwardx11‘)
config.write(open(‘test.ini‘,‘w‘))
#设置
config.set(‘bitbucket.org‘,‘user‘,‘gangdang‘)
config.write(open(‘test.ini‘,‘w‘))
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)
<?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数据
print(root.iter(‘year‘)) #全文搜索
print(root.find(‘country‘)) #在root的子节点找,只找一个
print(root.findall(‘country‘)) #在root的子节点找,找所有
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,child.attrib[‘name‘])
for i in child:
print(i.tag,i.attrib,i.text)
#只遍历year 节点
for node in root.iter(‘year‘):
print(node.tag,node.text)
#---------------------------------------
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‘)
node.set(‘version‘,‘1.0‘)
tree.write(‘test.xml‘)
#删除node
for country in root.findall(‘country‘):
rank = int(country.find(‘rank‘).text)
if rank > 50:
root.remove(country)
tree.write(‘output.xml‘)
#在country内添加(append)节点year2
import xml.etree.ElementTree as ET
tree = ET.parse("a.xml")
root=tree.getroot()
for country in root.findall(‘country‘):
for year in country.findall(‘year‘):
if int(year.text) > 2000:
year2=ET.Element(‘year2‘)
year2.text=‘新年‘
year2.attrib={‘update‘:‘yes‘}
country.append(year2) #往country节点下添加子节点
tree.write(‘a.xml.swap‘)
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) #打印生成的格式
import hashlib
m=hashlib.md5()
m.update(‘hello‘.encode(‘utf-8‘))
print(m.hexdigest())
#->运行结果:
5d41402abc4b2a76b9719d911017c592
a.txt文件内容:12345
import hashlib
m = hashlib.md5()
with open(r‘F:\oldboy_python\objects\day06\练习\a.txt‘, ‘rb‘) as f:
for line in f:
m.update(line)
md5_num = m.hexdigest()
print(md5_num)
#->
827ccb0eea8a706c4c34a16891f84e7b
import hashlib
hash = hashlib.sha256()
hash.update(‘hello‘.encode(‘utf-8‘))
print(‘--->‘, hash.hexdigest())
hash = hashlib.sha256(‘hello‘.encode(‘utf-8‘))
hash.update(‘123‘.encode(‘utf8‘))
print(‘===>‘, hash.hexdigest())
#->
---> 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
===> 27cc6994fc1c01ce6659c6bddca9b69c4c6a9418065e612c69d110b3f7b11f8a
import hashlib
passwds=[
‘alex3714‘,
‘alex1313‘,
‘alex94139413‘,
‘alex123456‘,
‘123456alex‘,
‘a123lex‘,
]
def make_passwd_dic(passwds):
dic = {}
for passwd in passwds:
m = hashlib.md5()
m.update(passwd.encode(‘utf-8‘))
dic[passwd] = m.hexdigest()
return dic
def break_code(cryptograph,passwd_dic):
"""
cryptograph:为抓取到的密文密码
:param cryptograph:
:param passwd_dic:
:return:
"""
for k, v in passwd_dic.items():
if v == cryptograph:
print(‘密码是===>\033[46m%s\033[0m‘ %k)
cryptograph = ‘aee949757a2e698417463d47acac93df‘
#此处模拟alex3714经过md5算法产生的密文密码break_code(cryptograph, make_passwd_dic(passwds))
运行结果:
密码是===>alex3714
标签:包含 内容 重要 分割文件 rand 等等 tag 完全 int
原文地址:http://www.cnblogs.com/xiaofeiweb/p/6973809.html