⼀.简介
模块是⼀个保存了Python代码的⽂件。模块能定义函数,类和变量。模块⾥也能包含可执⾏的代码 模块分为三种:
⾃定义模块内置标准模块
开源模块(第三⽅)⾃定义模块:
模块导⼊
import module
from module.xx.xx import xx
from module.xx.xx import xx as rename from module.xx.xx import *
导⼊⾃定义模块时注意路径,查看库⽂件sys.path,sys.path.append('路径')添加⾃定义路径⼆.内置模块time模块
time模块提供各种操作时间的函数
说明:⼀般有两种表⽰时间的⽅式:
1.时间戳的⽅式(相对于1970.1.1 00:00:00以秒计算的偏移量),时间戳是惟⼀的
2.以数组的形式表⽰即(struct_time),共有九个元素,分别表⽰,同⼀个时间戳的struct_time会因为时区不同⽽不同
The tuple items are:
year (including century, e.g. 1998) month (1-12) day (1-31) hours (0-23) minutes (0-59) seconds (0-59)
weekday (0-6, Monday is 0)
Julian day (day in the year, 1-366)
DST (Daylight Savings Time) flag (-1, 0 or 1)
函数
time() -- 返回时间戳
sleep() -- 延迟运⾏单位为s
gmtime() -- 转换时间戳为时间元组(时间对象)localtime() -- 转换时间戳为本地时间对象asctime() -- 将时间对象转换为字符串ctime() -- 将时间戳转换为字符串mktime() -- 将本地时间转换为时间戳
strftime() -- 将时间对象转换为规范性字符串常⽤的格式代码:%Y Year with century as a decimal number.%m Month as a decimal number [01,12].
%d Day of the month as a decimal number [01,31].%H Hour (24-hour clock) as a decimal number [00,23].%M Minute as a decimal number [00,59].%S Second as a decimal number [00,61].%z Time zone offset from UTC.
%a Locale's abbreviated weekday name.%A Locale's full weekday name.
%b Locale's abbreviated month name.%B Locale's full month name.
%c Locale's appropriate date and time representation.%I Hour (12-hour clock) as a decimal number [01,12].%p Locale's equivalent of either AM or PM.
strptime() -- 将时间字符串根据指定的格式化符转换成数组形式的时间常⽤格式代码: 同strftime
举例
#!/usr/bin/env python# -*- coding:utf-8 -*-import time
#返回当前时间戳print(time.time())#返回当前时间print(time.ctime())
#将时间戳转换为字符串
print(time.ctime(time.time()-860))#本地时间
print(time.localtime(time.time()-800))
#与time.localtime()功能相反,将struct_time格式转回成时间戳格式print(time.mktime(time.localtime()))
#将struct_time格式转成指定的字符串格式
print(time.strftime(\"%Y-%m-%d %H:%M:%S\",time.gmtime()))#将字符串格式转换成struct_time格式
print(time.strptime(\"2016-01-28\",\"%Y-%m-%d\"))#休眠5s
time.sleep(5)
View Code2.datetime模块
定义的类有:
datetime.date --表⽰⽇期的类。常⽤的属性有year, month, day
datetime.time --表⽰时间的类。常⽤的属性有hour, minute, second, microseconddatetime.datetime --表⽰⽇期时间
datetime.timedelta --表⽰时间间隔,即两个时间点之间的长度date类
date类表⽰⽇期,构造函数如下 :datetime.date(year, month, day);
year (1-9999)month (1-12)day (1-31)
date.today() --返回⼀个表⽰当前本地⽇期的date对象
date.fromtimestamp(timestamp) --根据给定的时间戮,返回⼀个date对象
#根据给定的时间戮,返回⼀个date对象
print(datetime.date.fromtimestamp(time.time()))#返回⼀个表⽰当前本地⽇期的date对象print(datetime.datetime.today())
View Code
date.year() --取给定时间的年 date.month() --取时间对象的⽉ date.day() --取给定时间的⽇
date.replace() --⽣成⼀个新的⽇期对象,⽤参数指定的年,⽉,⽇代替原有对象中的属性date.timetuple() --返回⽇期对应的time.struct_time对象date.weekday() --返回weekday,Monday == 0 ... Sunday == 6date.isoweekday() --返回weekday,Monday == 1 ... Sunday == 7date.ctime() --返回给定时间的字符串格式
import datetime
from dateutil.relativedelta import relativedelta# 获取当前时间的前⼀个⽉
datetime.datetime.now() - relativedelta(months=+1)# 获取当天的前⼀个⽉
datetime.date.today() - relativedelta(months=+1)
#取时间对象的年
print(datetime.date.today().year)#取时间对象的⽉
print(datetime.date.today().month)#取时间对象的⽇
print(datetime.date.today().day)
#⽣成⼀个新的⽇期对象,⽤参数指定的年,⽉,⽇代替原有对象中的属性print(datetime.date.today().replace(2010,6,12))#返回给定时间的时间元组/对象
print(datetime.date.today().timetuple())#返回weekday,从0开始
print(datetime.date.today().weekday())#返回weekday,从1开始
print(datetime.date.today().isoweekday())#返回给定时间的字符串格式
print(datetime.date.today().ctime())
View Code
time 类
time类表⽰时间,由时、分、秒以及微秒组成
time.min() --最⼩表⽰时间time.max() --最⼤表⽰时间time.resolution() --微秒
#最⼤时间
print(datetime.time.max)#最⼩时间
print(datetime.time.min)#时间最⼩单位,微秒
print(datetime.time.resolution)
View Code
datetime类
datetime是date与time的结合体,包括date与time的所有信息datetime.max() --最⼤值datetime.min() --最⼩值
datetime.resolution() --datetime最⼩单位
datetime.today() --返回⼀个表⽰当前本地时间
datetime.fromtimestamp() --根据给定的时间戮,返回⼀个datetime对象datetime.year() --取年datetime.month() --取⽉datetime.day() --取⽇期datetime.replace() --替换时间
datetime.strptime() --将字符串转换成⽇期格式datetime.time() --取给定⽇期时间的时间
#datetime最⼤值
print(datetime.datetime.max)#datetime最⼩值
print(datetime.datetime.min)#datetime最⼩单位
print(datetime.datetime.resolution)#返回⼀个表⽰当前本地时间print(datetime.datetime.today())
#根据给定的时间戮,返回⼀个datetime对象
print(datetime.datetime.fromtimestamp(time.time()))#取时间对象的年
print(datetime.datetime.now().year)#取时间对象的⽉
print(datetime.datetime.now().month)#取时间对象的⽇
print(datetime.datetime.now().day)
#⽣成⼀个新的⽇期对象,⽤参数指定的年,⽉,⽇代替原有对象中的属性print(datetime.datetime.now().replace(2010,6,12))#返回给定时间的时间元组/对象
print(datetime.datetime.now().timetuple())#返回weekday,从0开始
print(datetime.datetime.now().weekday())#返回weekday,从1开始
print(datetime.datetime.now().isoweekday())#返回给定时间的字符串格式
print(datetime.datetime.now().ctime())#将字符串转换成⽇期格式
print(datetime.datetime.strptime(\"21/11/06 16:30\", \"%d/%m/%y %H:%M\"))#取给定⽇期时间的时间
print(datetime.datetime.now().time())#获取5⽇前时间
print(datetime.datetime.now() + datetime.timedelta(days=-5))
View Code
3.sys模块
⽤于提供对解释器相关的访问及维护,并有很强的交互功能
常⽤函数:
sys.argv --传参,第⼀个参数为脚本名称即argv[0]sys.path --模块搜索路径sys.moudule --加载模块字典sys.stdin --标准输⼊sys.stdout --标准输出sys.stderr --错误输出sys.platform --返回系统平台名称sys.version --查看python版本sys.maxsize --最⼤的Int值举例:
#!/usr/bin/env python# -*- coding:utf-8 -*-#传参
import sysprint(sys.argv[0])print(sys.argv[1])print(sys.argv[2])
##运⾏
python argv.py argv0 argv1argv.pyargv0argv1
#!/usr/bin/env python# -*- coding:utf-8 -*-import sys,os
dirname = sys.stdin.read()os.mkdir(dirname.strip())
View Code
#sys.exit()系统返回值 >>> import sys>>> sys.exit(0)
C:\\>echo %ERRORLEVEL%0
#windows查看系统返回值命令echo %ERRORLEVEL%#linux查看系统返回值命令echo $?
>>> import sys>>> sys.platform
'win32'
>>> sys.version
'3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 bit (AMD)]'>>> sys.maxsize
9223372036854775807
View Code
import sys,timefor i in range(100): sys.stdout.write('r')
sys.stdout.write('%s%% |%s' % (int(i/100*100),int(i/100*100) * '*')) sys.stdout.flush time.sleep(0.2)
View Code
4.pickle模块
pickle,⽤于python特有的类型 和 python的数据类型间进⾏转换
pickle模块提供了四个功能:dumps、dump、loads、load
Functions:
dump(object, file)
dumps(object) -> string load(file) -> object loads(string) -> object
pickle.dumps(obj)--把任意对象序列化成⼀个str,然后,把这个str写⼊⽂件pickle.loads(string) --反序列化出对象
pickle.dump(obj,file) --直接把对象序列化后写⼊⽂件pickle.load(file) --从⽂件中反序列化出对象
#!/usr/bin/env python# -*- coding:utf-8 -*-import pickleaccounts = { 1000: {
'name':'USERA',
'email': 'lijie3721@126.com', 'passwd': 'abc123', 'balance': 15000,
'phone': 13651054608, 'bank_acc':{
'ICBC':14324234, 'CBC' : 235234, 'ABC' : 35235423 } },
1001: {
'name': 'USERB',
'email': 'caixin@126.com', 'passwd': 'abc145323', 'balance': -15000, 'phone': 1345635345, 'bank_acc': {
'ICBC': 4334343, } },}
#把字典类型写⼊到⽂件中f = open('accounts.db','wb')
f.write(pickle.dumps(accounts))f.close()
#2,反序列出对象并修改其内容,并将修改内容重新写⼊⽂件file_name = \"accounts.db\"f = open(file_name,'rb')
account_dic = pickle.loads(f.read())f.close()
account_dic[1000]['balance'] -= 500f = open(file_name,'wb')
f.write(pickle.dumps(account_dic))f.close()
#3,反序列化对象并查看其内容f = open('accounts.db','rb')
acountdb = pickle.loads(f.read())print(acountdb)
dic = {
'k1': [1,2], 'k2': [3,4]}
#1.将对象写⼊⽂件f = open('test','wb')pickle.dump(dic,f)f.close()
#2.将⽂件中内容反序列化,并读出f = open('test','rb')dic2 = pickle.load(f)print(dic2)f.close()
5.os模块
作⽤:
⽤于提供系统级别的操作函数:
1 os.getcwd() 获取当前⼯作⽬录,即当前python脚本⼯作的⽬录路径 2 os.chdir(\"dirname\") 改变当前脚本⼯作⽬录;相当于shell下cd 3 os.curdir 返回当前⽬录: ('.')
4 os.pardir 获取当前⽬录的⽗⽬录字符串名:('..') 5 os.makedirs('dir1/dir2') 可⽣成多层递归⽬录
6 os.removedirs('dirname1') 若⽬录为空,则删除,并递归到上⼀级⽬录,如若也为空,则删除,依此类推 7 os.mkdir('dirname') ⽣成单级⽬录;相当于shell中mkdir dirname
8 os.rmdir('dirname') 删除单级空⽬录,若⽬录不为空则⽆法删除,报错;相当于shell中rmdir dirname 9 os.listdir('dirname') 列出指定⽬录下的所有⽂件和⼦⽬录,包括隐藏⽂件,并以列表⽅式打印10 os.remove() 删除⼀个⽂件
11 os.rename(\"oldname\重命名⽂件/⽬录12 os.stat('path/filename') 获取⽂件/⽬录信息
13 os.sep 操作系统特定的路径分隔符,win下为\"\\\\\下为\"/\"14 os.linesep 当前平台使⽤的⾏终⽌符,win下为\"\\\n\下为\"\\n\"15 os.pathsep ⽤于分割⽂件路径的字符串
16 os.name 字符串指⽰当前使⽤平台。win->'nt'; Linux->'posix'17 os.system(\"bash command\") 运⾏shell命令,直接显⽰18 os.environ 获取系统环境变量
19 os.path.abspath(path) 返回path规范化的绝对路径
20 os.path.split(path) 将path分割成⽬录和⽂件名⼆元组返回
21 os.path.dirname(path) 返回path的⽬录。其实就是os.path.split(path)的第⼀个元素
22 os.path.basename(path) 返回path最后的⽂件名。如何path以/或\\结尾,那么就会返回空值。即os.path.split(path)的第⼆个元素23 os.path.exists(path) 如果path存在,返回True;如果path不存在,返回False24 os.path.isabs(path) 如果path是绝对路径,返回True
25 os.path.isfile(path) 如果path是⼀个存在的⽂件,返回True。否则返回False26 os.path.isdir(path) 如果path是⼀个存在的⽬录,则返回True。否则返回False
27 os.path.join(path1[, path2[, ...]]) 将多个路径组合后返回,第⼀个绝对路径之前的参数将被忽略28 os.path.getatime(path) 返回path所指向的⽂件或者⽬录的最后存取时间29 os.path.getmtime(path) 返回path所指向的⽂件或者⽬录的最后修改时间
6.hashlib模块
作⽤:
⽤于加密相关的操作,代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法
import hashlib
# ######## md5 ########hash = hashlib.md5()# help(hash.update)
hash.update(bytes('admin', encoding='utf-8'))print(hash.hexdigest())print(hash.digest())
######## sha1 ########
hash = hashlib.sha1()
hash.update(bytes('admin', encoding='utf-8'))
print(hash.hexdigest())
# ######## sha256 ########
hash = hashlib.sha256()
hash.update(bytes('admin', encoding='utf-8'))print(hash.hexdigest())
# ######## sha384 ########
hash = hashlib.sha384()
hash.update(bytes('admin', encoding='utf-8'))print(hash.hexdigest())
# ######## sha512 ########
hash = hashlib.sha512()
hash.update(bytes('admin', encoding='utf-8'))print(hash.hexdigest())
View Code
加密算法缺陷,即:通过撞库可以反解。所以,有必要对加密算法中添加⾃定义key再来做加密
import hashlib
# ######## md5 ########
hash = hashlib.md5(bytes('8oaFs09f',encoding=\"utf-8\"))hash.update(bytes('admin',encoding=\"utf-8\"))print(hash.hexdigest())
View Code
7.random
作⽤: ⽣成随机变量
import random
print(random.random())print(random.randint(1, 2))print(random.randrange(1, 10))
import randomcheckcode = ''for i in range(4):
current = random.randrange(0,4) if current != i:
temp = chr(random.randint(65,90)) else:
temp = random.randint(0,9) checkcode += str(temp)print checkcode
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- huatuo9.cn 版权所有 赣ICP备2023008801号-1
违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务