Random模块:

#!/usr/bin/env python
#_*_encoding: utf-8_*_
import random
print (random.random()) #0.6445010863311293
#random.random()用于生成一个0到1的随机符点数: 0 <= n < 1.0
print (random.randint(1,7)) #
#random.randint()的函数原型为:random.randint(a, b),用于生成一个指定范围内的整数。
# 其中参数a是下限,参数b是上限,生成的随机数n: a <= n <= b
print (random.randrange(1,10)) #
#random.randrange的函数原型为:random.randrange([start], stop[, step]),
# 从指定范围内,按指定基数递增的集合中 获取一个随机数。如:random.randrange(10, 100, 2),
# 结果相当于从[10, 12, 14, 16, ... 96, 98]序列中获取一个随机数。
# random.randrange(10, 100, 2)在结果上与 random.choice(range(10, 100, 2) 等效。
print(random.choice('liukuni')) #i
#random.choice从序列中获取一个随机元素。
# 其函数原型为:random.choice(sequence)。参数sequence表示一个有序类型。
# 这里要说明一下:sequence在python不是一种特定的类型,而是泛指一系列的类型。
# list, tuple, 字符串都属于sequence。有关sequence可以查看python手册数据模型这一章。
# 下面是使用choice的一些例子:
print(random.choice("学习Python"))#学
print(random.choice(["JGood","is","a","handsome","boy"])) #List
print(random.choice(("Tuple","List","Dict"))) #List
print(random.sample([1,2,3,4,5],3)) #[1, 2, 5]
#random.sample的函数原型为:random.sample(sequence, k),从指定序列中随机获取指定长度的片断。sample函数不会修改原有序列。 #############Random模块实际应用##########
#随机整数:
print( random.randint(0,99)) # #随机选取0到100间的偶数:
print(random.randrange(0, 101, 2)) # #随机浮点数:
print( random.random()) #0.2746445568079129
print(random.uniform(1, 10)) #9.887001463194844 #随机字符:
print(random.choice('abcdefg&#%^*f')) #f #多个字符中选取特定数量的字符:
print(random.sample('abcdefghij',3)) #['f', 'h', 'd'] #随机选取字符串:
print( random.choice ( ['apple', 'pear', 'peach', 'orange', 'lemon'] )) #apple
#洗牌#
items = [1,2,3,4,5,6,7]
print(items) #[1, 2, 3, 4, 5, 6, 7]
random.shuffle(items)
print(items) #[1, 4, 7, 2, 5, 3, 6]

xml模块:

<?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数据

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)
for i in child:
print(i.tag,i.text) #只遍历year 节点
for node in root.iter('year'):
print(node.tag,node.text)

遍历XML

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") tree.write("xmltest.xml") #删除node
for country in root.findall('country'):
rank = int(country.find('rank').text)
if rank > 50:
root.remove(country) tree.write('output.xml')

XML修改删除

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 = ''
name2 = ET.SubElement(new_xml,"name",attrib={"enrolled":"no"})
age = ET.SubElement(name2,"age")
age.text = '' et = ET.ElementTree(new_xml) #生成文档对象
et.write("test.xml", encoding="utf-8",xml_declaration=True) ET.dump(new_xml) #打印生成的格式

创建XML

json模块:

'''
json模块
1、把内存中的数据类型序列化为字符串或者字符串反序列化
2、用于不同的平台之间的数据交换,所以序列化的对象类型应是通用的
例如:字符串、列表、字典
3、一次dump,一次load
''' #################json序列化#################
import json
f = open('test.txt','w')
info = {'name':'alex','age':22}
json.dump(info,f,ensure_ascii=False) #等价于 f.write(json.dumps(info, ensure_ascii=False)) ensure_ascii防止中文乱码
f.close() #test.txt中存放{'name': 'alex', 'age': 22}
#################json反序列化#################
f = open('test.txt','r')
data = json.load(f) #等价于 f.loads(f.read())
print(data['name']) # alex

pickle模块:

'''
pickle模块:
1、只能Python中使用
2、可存放所有对象
3、一次dump,一次load
'''
##################pickle序列化##################
import pickle
def sayhi(name):
print('hello',name)
info = {'func':sayhi}
f = open('test.txt','wb')
pickle.dump(info,f) # 或者 f.write(pickle.dumps(info))
f.close() # 序列化为二进制文件
##################pickle反序列化##################
f = open('test.txt','rb')
data = pickle.load(f) # 或者pickle.loads(f.read())
data['func']('alex') # hello,alex

shelve模块:

'''
shelve模块
可以让你一次dump很多对象,取的时候按名称取。shelve是对pickle更上一层的封装
''' import shelve
import datetime
#####################序列化#######################
d = shelve.open("test")
info = {'name':'alex','age':22}
pets = {'dog','cat'}
d['info'] = info
d['pets'] = pets
d['date'] = datetime.datetime.now() #####################反序列化#######################
d = shelve.open("test")
print(d.get('info')) # {'name': 'alex', 'age': 22}
print(d.get('pets')) # {'dog', 'cat'}
print(d.get('date')) # 2018-07-17 22:43:41.091981

time模块

'''
时间的表示格式:
1、格式化字符串"2018-07-01 13:45:557"
2、时间戳,从1970-1-1到现在的秒数1531908307.0743685
3、元祖,time.localtime() 年月日时分秒等元素
时区UTC+8
'''
import time
time.time() #获取时间戳,float
time.sleep(2) #暂停2毫秒
time.gmtime(1000) #时间戳1000秒==>为元祖的表示形式UTC
time.localtime(1000) #时间戳1000秒==>为元祖表示形式UTC+8
time.mktime(tuple) #传入元祖==>时间戳
time.strftime("%Y-%m-%d",tuple) #元祖==>格式化字符串
time.strptime("2016-09-02","%Y-%m-%d") #格式化字符串==>为元祖
time.asctime(tuple) #把元祖==>Sat Aug 20 14:59:45 2016格式表示
time.ctime(3232342) #把时间戳==>Sat Aug 20 14:59:45 2016格式表示

datetime模块

import datetime

print(datetime.datetime.now()) #返回 2016-08-19 12:47:03.941925
print(datetime.date.fromtimestamp(time.time()) ) # 时间戳直接转成日期格式 2016-08-19
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=3)) #当前时间+3小时
print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #当前时间+30分 c_time = datetime.datetime.now()
print(c_time.replace(minute=3,hour=2)) #时间替换

os模块

import os
os.getcwd() #获取当前工作目录,即pwd
os.chdir("dirname") #改变当前脚本工作目录;相当于shell下cd
os.curdir #返回当前目录: ('.')
os.pardir #获取当前目录的父目录字符串名:('..')
os.makedirs('dirname1/dirname2') #可生成多层递归目录
os.removedirs('dirname1') #只能删空目录,为空则删除并递归到上一级目录,如若也为空,则删除,依此类推
os.mkdir('dirname') #生成单级目录;相当于shell中mkdir dirname
os.rmdir('dirname') #删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
os.listdir('dirname') #列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
os.remove() #删除一个文件
os.rename("oldname","newname") #重命名文件/目录
os.stat('path/filename') #获取文件/目录信息
os.sep #输出操作系统特定的路径分隔符,win下为"\\",Linux下为"/"
os.linesep #输出当前平台使用的行终止符,win下为"\t\n",Linux下为"\n"
os.pathsep #输出分隔环境变量path的分隔符,win下为; Linux下为:
os.name #输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
os.system("bash command") #运行shell命令,直接显示
os.environ #获取系统环境变量
os.path.abspath(path) #返回path规范化的绝对路径
os.path.split(path) #将path分割成目录和文件名二元组返回
os.path.dirname(path) #返回path的目录。其实就是os.path.split(path)的第一个元素
os.path.basename(path) #返回path最后的文件名。如果path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
os.path.exists(path) #如果path存在,返回True;如果path不存在,返回False
os.path.isabs(path) #如果path是绝对路径,返回True
os.path.isfile(path) #如果path是一个存在的文件,返回True。否则返回False
os.path.isdir(path) #如果path是一个存在的目录,则返回True。否则返回False
os.path.join(path1[, path2[, ...]]) #将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
os.path.getatime(path) #返回path所指向的文件或者目录的最后存取时间
os.path.getmtime(path) #返回path所指向的文件或者目录的最后修改时间

sys模块

sys.argv           #命令行参数List,第一个元素是程序本身路径
sys.exit(n) #退出程序,正常退出时exit(0)
sys.version #获取Python解释程序的版本信息
sys.maxint #最大的Int值
sys.path #返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform #返回操作系统平台名称
sys.stdout.write('please:')
val = sys.stdin.readline()[:-1]

shutil模块:进行压缩和解压的模块,拷贝文件删除文件等

直接参考http://www.cnblogs.com/wupeiqi/articles/4963027.html

pyYAMAL模块

/etc/http/conf/http.conf:
file.managed:
- source: salt://apache/http.conf
- user: root
- group: root
- mode: 644
- attrs: ai
- template: jinja
- defaults:
custom_var: "default value"
other_var: 123
{% if grains['os'] == 'Ubuntu' %}
- context:
custom_var: "override"
{% endif %}

YAMAL格式配置文件

参考文档:http://pyyaml.org/wiki/PyYAMLDocumentation

configparser模块

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes [bitbucket.org]
User = hg [topsecret.server.com]
Port = 50022
ForwardX11 = no

ConfigParser配置文件

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)

生成ConfigParser配置文件

>>> import configparser
>>> config = configparser.ConfigParser()
>>> config.sections()
[]
>>> config.read('example.ini')
['example.ini']
>>> config.sections()
['bitbucket.org', 'topsecret.server.com']
>>> 'bitbucket.org' in config
True
>>> 'bytebong.com' in config
False
>>> config['bitbucket.org']['User']
'hg'
>>> config['DEFAULT']['Compression']
'yes'
>>> topsecret = config['topsecret.server.com']
>>> topsecret['ForwardX11']
'no'
>>> topsecret['Port']
''
>>> for key in config['bitbucket.org']: print(key)
...
user
compressionlevel
serveraliveinterval
compression
forwardx11
>>> config['bitbucket.org']['ForwardX11']
'yes'

读ConfigParser配置

[section1]
k1 = v1
k2:v2 [section2]
k1 = v1 import ConfigParser config = ConfigParser.ConfigParser()
config.read('i.cfg') # ########## 读 ##########
#secs = config.sections()
#print secs
#options = config.options('group2')
#print options #item_list = config.items('group2')
#print item_list #val = config.get('group1','key')
#val = config.getint('group1','key') # ########## 改写 ##########
#sec = config.remove_section('group1')
#config.write(open('i.cfg', "w")) #sec = config.has_section('wupeiqi')
#sec = config.add_section('wupeiqi')
#config.write(open('i.cfg', "w")) #config.set('group2','k1',11111)
#config.write(open('i.cfg', "w")) #config.remove_option('group2','age')
#config.write(open('i.cfg', "w"))

修改ConfigParser配置

hashlib模块:用于计算对象的hash值的相关操作,3.x里代替了md5模块和sha模块,主要提供sha1,sha224,sha256,sha384,sha512,md5加密算法

import hashlib

m = hashlib.md5()
m.update(b"Hello")
m.update(b"It's me")
print(m.digest())
########简便写法###########
hashlib.md5("abc".encode()).digest()
########################
m.update(b"It's been a long time since last time we ...") print(m.digest()) #2进制格式hash
print(len(m.hexdigest())) #16进制格式hash
'''
def digest(self, *args, **kwargs): # real signature unknown
""" Return the digest value as a string of binary data. """
pass def hexdigest(self, *args, **kwargs): # real signature unknown
""" Return the digest value as a string of hexadecimal digits. """
pass '''
import hashlib # ######## md5 ######## hash = hashlib.md5()
hash.update('admin')
print(hash.hexdigest()) # ######## sha1 ######## hash = hashlib.sha1()
hash.update('admin')
print(hash.hexdigest()) # ######## sha256 ######## hash = hashlib.sha256()
hash.update('admin')
print(hash.hexdigest()) # ######## sha384 ######## hash = hashlib.sha384()
hash.update('admin')
print(hash.hexdigest()) # ######## sha512 ######## hash = hashlib.sha512()
hash.update('admin')
print(hash.hexdigest())

hashlib

'''
python 还有一个 hmac 模块,它内部对我们创建 key 和 内容 再进行处理然后再加密
散列消息鉴别码,简称HMAC,是一种基于消息鉴别码MAC(Message Authentication Code)的鉴别机制。
使用HMAC时,消息通讯的双方,通过验证消息中加入的鉴别密钥K来鉴别消息的真伪;
一般用于网络通信中消息加密,前提是双方先要约定好key,就像接头暗号一样,
然后消息发送把用key把消息加密,接收方用key + 消息明文再加密,
拿加密后的值 跟 发送者的相对比是否相等,这样就能验证消息的真实性,及发送者的合法性了。
'''
import hmac
h = hmac.new(b'abcd', '你好'.encode(encoding="utf-8"))
print(h.hexdigest())

双重加密

模块简介:(random)(xml,json,pickle,shelve)(time,datetime)(os,sys)(shutil)(pyYamal,configparser)(hashlib)的更多相关文章

  1. Python常用模块(logging&re&时间&random&os&sys&shutil&序列化&configparser&&hashlib)

    一. logging(日志模块) 二 .re模块 三. 时间模块 四. random模块 五. os模块 六. sys模块 七. shutil模块 八. 序列化模块(json&pickle&a ...

  2. python 常用模块 time random os模块 sys模块 json & pickle shelve模块 xml模块 configparser hashlib subprocess logging re正则

    python 常用模块 time random os模块 sys模块 json & pickle shelve模块 xml模块 configparser hashlib  subprocess ...

  3. 模块 - json/pickle/shelve/xml/configparser

    序列化: 序列化是指把内存里的数据类型转变成字符串,以使其能存储到硬盘或通过网络传输到远程,因为硬盘或网络传输时只能接受bytes. 为什么要序列化: 有种办法可以直接把内存数据(eg:10个列表,3 ...

  4. 常用模块(random,os,json,pickle,shelve)

    常用模块(random,os,json,pickle,shelve) random import random print(random.random()) # 0-1之间的小数 print(rand ...

  5. python序列化: json & pickle & shelve 模块

    一.json & pickle & shelve 模块 json,用于字符串 和 python数据类型间进行转换pickle,用于python特有的类型 和 python的数据类型间进 ...

  6. python 全栈开发,Day25(复习,序列化模块json,pickle,shelve,hashlib模块)

    一.复习 反射 必须会 必须能看懂 必须知道在哪儿用 hasattr getattr setattr delattr内置方法 必须能看懂 能用尽量用__len__ len(obj)的结果依赖于obj. ...

  7. day6_python序列化之 json & pickle & shelve 模块

    一.json & pickle & shelve 模块 json,用于字符串 和 python数据类型间进行转换pickle,用于python特有的类型 和 python的数据类型间进 ...

  8. oldboy edu python full stack s22 day16 模块 random time datetime os sys hashlib collections

    今日内容笔记和代码: https://github.com/libo-sober/LearnPython/tree/master/day13 昨日内容回顾 自定义模块 模块的两种执行方式 __name ...

  9. Python学习笔记——基础篇【第六周】——json & pickle & shelve & xml处理模块

    json & pickle 模块(序列化) json和pickle都是序列化内存数据到文件 json和pickle的区别是: json是所有语言通用的,但是只能序列化最基本的数据类型(字符串. ...

随机推荐

  1. 实现网站页面的QQ临时会话,分享到空间微博等按钮.

    一 qq临时会话 要实现qq临时会话首先要到qq在线状态官网开通qq在线状态,其中临时对话也分为加密和未加密. 1.1:加密模式 <a target="_blank" hre ...

  2. .NET Core中的CSV解析库

    感谢 本篇首先特别感谢从此启程兄的<.NetCore外国一些高质量博客分享>, 发现很多国外的.NET Core技术博客资源, 我会不定期从中选择一些有意思的文章翻译总结一下. .NET ...

  3. vue和react的介绍

    这几年前端框架发展的不错,出了不少框架,像微软自己的knockoutjs,angular,vue和最近比较火的react等,之前我有写过前两者的相关文章,今天主要说一下后两者. 介绍 是一个用于构建用 ...

  4. ARP协议分析

    一.ARP概述 网络中所有的协议(HTTP.URL.FTP.TELNET.TCP.UDP.ARP ······)都包含在TCP/IP协议栈中,从使用上来看:其中大部分协议都是大家平常上网所接触到的,不 ...

  5. windows查看端口占用 windows端口占用 查找端口占用程序 强制结束端口占用 查看某个端口被占用的解决方法 如何查看Windows下端口占用情况

    windows下查询端口占用情况 ,强制结束端口占用程序 查询8080端口被那个程序占用 如何强制结束windows下端口占用情况? 下面操作在win10下 在控制台执行命令   1.列出所有端口的情 ...

  6. Shiro源码分析之SecurityManager对象获取

    目录 SecurityManager获取过程 1.SecurityManager接口介绍 2.SecurityManager实例化时序图 3.源码分析 4.总结 @   上篇文章Shiro源码分析之获 ...

  7. pl/sql to_date

    to_date 函数:TO_DATE( string1 [, format_mask] [, nls_language] ) 后面两个函数为可选 ,意思将字符串类型转换为时间类型 , 可以自定义时间格 ...

  8. 初识 MongoDB,MongoDB 的安装运行

    1.  MongoDB 非关系型数据库  MongoDB是一个基于分布式文件存储的数据库,由C++语言编写.目的是为WEB应用提供扩展的高性能的数据存储解决方案.MongoDB是一个介于关系型数据库和 ...

  9. Java开发笔记(四十)日期与字符串的互相转换

    前面介绍了如何通过Date工具获取各个时间数值,但是用户更喜欢形如“2018-11-24 23:04:18”这种结构清晰.简洁明了的字符串,而非啰里八唆依次汇报每个时间单位及其数值的描述.既然日期时间 ...

  10. php设计模式--简单介绍

    鉴于最近有几个小伙伴总问一些设计模式相关的东西,本人借鉴了一些东西,准备将常见的几种php的设计模式总结整理出来. 平时我们用到的设计模式很多,建议大家多多读一些php开源框架,当深入的阅读了一些ph ...