首页 > 技术文章 > python ==》 模块

zhongbokun 2017-08-08 19:56 原文

今日内容:

  1.时间模块 (time)

  2.随机数 (random)

  3.sys模块

  4.os模块

  5.序列化模块

1.时间模块(time)

表示时间的三种方式:

  1.时间戳(timestamp)

  2.格式化的时间字符串(Format String) 

  3.元组(结构化) (struct time)

1.时间戳:

time.sleep()  #使程序滞留一段时间,该时间以 秒 为单位。
time.time()  #时间戳, 即 记录某个时间点

2.格式化时间字符串的各种参数用法:如下

%y 两位数的年份表示(00-99%Y 四位数的年份表示(000-9999%m 月份(01-12%d 月内中的一天(0-31%H 24小时制小时数(0-23%I 12小时制小时数(01-12%M 分钟数(00=59%S 秒(00-59%a 本地简化星期名称
%A 本地完整星期名称
%b 本地简化的月份名称
%B 本地完整的月份名称
%c 本地相应的日期表示和时间表示
%j 年内的一天(001-366%p 本地A.M.或P.M.的等价符
%U 一年中的星期数(00-53)星期天为星期的开始
%w 星期(0-6),星期天为星期的开始
%W 一年中的星期数(00-53)星期一为星期的开始
%x 本地相应的日期表示
%X 本地相应的时间表示
%Z 当前时区的名称
%% %号本身


print(time.strftime('%Y.%m.%d %X'))
print(time.strftime('%Y.%m.%d %x'))
print(time.strftime('%y%m%d %H%M%S '))
print(time.strftime('%y%m%d %I%M%S %a'))
print(time.strftime('%y%m%d %I%M%S %A'))
print(time.strftime('%y%m%d %I%M%S %A %b'))
print(time.strftime('%y%m%d %I%M%S %A %B'))
print(time.strftime('%y%m%d %I%M%S %A %B %c'))
print(time.strftime('%y%m%d %I%M%S %A %B %c %j'))
print(time.strftime('%y%m%d %I%M%S %A %B %c %j %p'))
print(time.strftime('%y%m%d %I%M%S %A %B %c %j %p %U'))
print(time.strftime('%y%m%d %I%M%S %A %B %c %j %p %U %w'))
print(time.strftime('%y%m%d %I%M%S %A %B %c %j %p %U %W'))
print(time.strftime('%y%m%d %I%M%S %A %B %c %j %p %U %W %Z'))




结果:
2017.08.08 18:51:58
2017.08.08 08/08/17
170808 185158 
170808 065158 Tue
170808 065158 Tuesday
170808 065158 Tuesday Aug
170808 065158 Tuesday August
170808 065158 Tuesday August Tue Aug  8 18:51:58 2017
170808 065158 Tuesday August Tue Aug  8 18:51:58 2017 220
170808 065158 Tuesday August Tue Aug  8 18:51:58 2017 220 PM
170808 065158 Tuesday August Tue Aug  8 18:51:58 2017 220 PM 32
170808 065158 Tuesday August Tue Aug  8 18:51:58 2017 220 PM 32 2
170808 065158 Tuesday August Tue Aug  8 18:51:58 2017 220 PM 32 32
170808 065158 Tuesday August Tue Aug  8 18:51:58 2017 220 PM 32 32 ?D1¨²¡À¨º¡Á?¨º¡À??
View Code

3.元组(结构化):struct_time元组共有9个元素共九个元素:(年,月,日,时,分,秒,一年中第几周,一年中第几天等)

m = time.localtime()   #类似命名元组  用于计算比对。
print(m)
print(m.tm_year)

结果:

time.struct_time(tm_year=2017, tm_mon=8, tm_mday=8, tm_hour=18, tm_min=54, tm_sec=21, tm_wday=1, tm_yday=220, tm_isdst=0)
2017

Process finished with exit code 0

 小结:时间戳是计算机能够识别的时间;时间字符串是人能够看懂的时间;元组则是用来操作时间的

三种格式之间的转换:

  1.时间戳(timestamp)

  2.格式化的时间字符串(Format String) 

  3.元组(结构化) (struct time)

#时间戳  转  结构化    和      结构化 转  时间戳
print(time.gmtime())   #伦敦时间
print(time.localtime()) #北京时间
s = time.gmtime(1500000000) #时间戳  转  结构化
d = time.localtime(1500000000) #时间戳  转  结构化
print(s)
print(d)
print(time.mktime(s))   #结构化 转  时间戳
print(time.mktime(d))  #结构化 转  时间戳

结果:
time.struct_time(tm_year=2017, tm_mon=8, tm_mday=8, tm_hour=11, tm_min=26, tm_sec=54, tm_wday=1, tm_yday=220, tm_isdst=0)

time.struct_time(tm_year=2017, tm_mon=8, tm_mday=8, tm_hour=19, tm_min=26, tm_sec=54, tm_wday=1, tm_yday=220, tm_isdst=0)

time.struct_time(tm_year=2017, tm_mon=7, tm_mday=14, tm_hour=2, tm_min=40, tm_sec=0, tm_wday=4, tm_yday=195, tm_isdst=0)

time.struct_time(tm_year=2017, tm_mon=7, tm_mday=14, tm_hour=10, tm_min=40, tm_sec=0, tm_wday=4, tm_yday=195, tm_isdst=0)

1499971200.0
1500000000.0

Process finished with exit code 0

#结构化  转  字符串    和   字符串  转   结构化
print(time.strftime('%Y%m%d %X'))  #结构化转 字符串
print(time.strptime('2017-03-16','%Y-%m-%d'))   #字符串  转   结构化

结果:
20170808 19:29:32
time.struct_time(tm_year=2017, tm_mon=3, tm_mday=16, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=75, tm_isdst=-1)

Process finished with exit code 0
View Code

2.随机数(random)模块:

import random
#随机小数
print(random.random()) #大于0且小于1的小数。
print(random.uniform(1,3)) #大于1小于3的小数

#随机整数
print(random.randint(1,5))  #随机1-5的之间的整数。顾头顾尾
print(random.randrange(10))
print(random.randrange(1,10,2))

#随机选择一个返回
print(random.choice([1,2,3,4,[11,111,1111],'zxc']))

#随机选择多个返回,返回的个数为函数的第二个参数
print(random.sample([1,2,3,4,[5,6,7,8]],2))  #任意返回多个值,后面参数2 是用户之间定义的。

#打乱列表顺序
item = [1,3,5,7,9]
print(item)
random.shuffle(item)
print(item)


结果:
0.8872507582462091
1.3964555681725257
1
3
7
4
[[5, 6, 7, 8], 4]
[1, 3, 5, 7, 9]
[7, 1, 3, 9, 5]

Process finished with exit code 0
1.写一个验证码 1.要有数字, 2,要有字母  3,一共四位  4 可以重复
拿字母,用acsii 码, 拿到后,就转换成字符串。 65-90 97-122。
第一种方法:
def v_code ():
    code = '' \
           ''
    for i in range (4):
        num = random.randint(0,9)
        alf = chr(random.randint(65,90))
        alp = chr(random.randint(97,122))
        add = random.choice([num,alf,alp])
        code = ''.join([code,str(add)])
    return code
print(v_code())


第二种方法:
list1 = list (range(10))
new_list = list(map(str,list1))
alf = list(range(65,91))
alp = list(range(95,123))
alf_l=[]
for i in range (65,91):
    alf = chr(i)
    alf_l.append(alf)
alp_l=[]
for i in range (95,123):
    alp = chr(i)
    alp_l.append(alp)
new_list.extend(alf_l)
new_list.extend(alp_l)
ret = []
ret = random.sample(new_list,4)
print(''.join(ret))
View Code

3.OS模块

 

'''
os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
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    输出用于分割文件路径的字符串 win下为;,Linux下为:
os.name    输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
os.system("bash command")  运行shell命令,直接显示
os.popen("bash command)  运行shell命令,获取执行结果
os.environ  获取系统环境变量

os.path
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所指向的文件或者目录的最后修改时间
os.path.getsize(path) 返回path的大小
'''

4.sys模块:

sys模块是与python解释器交互的一个接口

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

5.序列化模块:

什么叫序列化——将原本的字典、列表等内容转换成一个字符串的过程就叫做序列化

序列化的目的

1、以某种存储形式使自定义对象持久化
2、将对象从一个地方传递到另一个地方。
3、使程序更具维护性。

json:

  Json模块提供了四个功能:dumps、dump、loads、load

import json
d = {'k':1}
ret1= json.dumps(d)   #字典转字符串
print(ret1,type(ret1))
ret2= json.loads(ret1)   #字符串转字典
print(ret2,type(ret2))

f = open('json_file','w')
dic = {'k1':'v1','k2':'v2','k3':'v3'}
json.dump(dic,f)    #dump方法接收一个文件句柄,直接将字典转换成json字符串写入文件
f.close()
print(dic)

f = open('json_file')
dic2 = json.load(f)   #load方法接收一个文件句柄,直接将文件中的json字符串转换成数据结构返回
f.close()
print(type(dic2),dic2)

结果:
{"k": 1} <class 'str'>
{'k': 1} <class 'dict'>
{'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
<class 'dict'> {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}

Process finished with exit code 0
View Code

pickle:

用于序列化的两个模块

 

  • json,用于字符串 和 python数据类型间进行转换
  • pickle,用于python特有的类型 和 python的数据类型间进行转换

 

pickle模块提供了四个功能:dumps、dump(序列化,存)、loads(反序列化,读)、load  (不仅可以序列化字典,列表...可以把python中任意的数据类型序列化

这里我们要说明一下,json是一种所有的语言都可以识别的数据结构。
如果我们将一个字典或者序列化成了一个json存在文件里,那么java代码或者js代码也可以拿来用。
但是如果我们用pickle进行序列化,其他语言就不能读懂这是什么了~
所以,如果你序列化的内容是列表或者字典,我们非常推荐你使用json模块
但如果出于某种原因你不得不序列化其他的数据类型,而未来你还会用python对这个数据进行反序列化的话,那么就可以使用pickle

shelve:

shelve也是python提供给我们的序列化工具,比pickle用起来更简单一些。
shelve只提供给我们一个open方法,是用key来访问的,使用起来和字典类似。

import shelve
f = shelve.open('shelve_file')
f['key'] = {'int':10, 'float':9.5, 'string':'Sample data'}  #直接对文件句柄操作,就可以存入数据
f.close()

import shelve
f1 = shelve.open('shelve_file')
existing = f1['key']  #取出数据的时候也只需要直接用key获取即可,但是如果key不存在会报错
f1.close()
print(existing)
View Code

这个模块有个限制,它不支持多个应用同一时间往同一个DB进行写操作。所以当我们知道我们的应用如果只进行读操作,我们可以让shelve通过只读方式打开DB

import shelve
f = shelve.open('shelve_file', flag='r')
existing = f['key']
f.close()
print(existing)
View Code

由于shelve在默认情况下是不会记录待持久化对象的任何修改的,所以我们在shelve.open()时候需要修改默认参数,否则对象的修改不会保存。

import shelve
f1 = shelve.open('shelve_file')
print(f1['key'])
f1['key']['new_value'] = 'this was not here before'
f1.close()

f2 = shelve.open('shelve_file', writeback=True)
print(f2['key'])
f2['key']['new_value'] = 'this was not here before'
f2.close()
View Code

writeback方式有优点也有缺点。优点是减少了我们出错的概率,并且让对象的持久化对用户更加的透明了;但这种方式并不是所有的情况下都需要,首先,使用writeback以后,shelf在open()的时候会增加额外的内存消耗,并且当DB在close()的时候会将缓存中的每一个对象都写入到DB,这也会带来额外的等待时间。因为shelve没有办法知道缓存中哪些对象修改了,哪些对象没有修改,因此所有的对象都会被写入。

 

推荐阅读