常用模塊類型

time(時間)

   延遲綫程運行time.sleep(secs)

print(0)
time.sleep(5)#延遲綫程五秒
print(5)

時間戳(timestamp):time.time()
print(time.time())  #從1970年至今的時間以秒的形式輸出
当前时区时间time.localtime()
time_obj = time.localtime()
print(time_obj)
#time.struct_time(tm_year=2019, tm_mon=5, tm_mday=8, tm_hour=20,
tm_min=52, tm_sec=45, tm_wday=2, tm_yday=128, tm_isdst=0)
print(time.localtime(1557094569))  # 将时间戳转化成时间对象
格式化时间
(2019, 5, 6, 6, 16, 9, 0, 126, 0)
res = time.strftime("%Y-%m-%d %H:%M:%S")
print(res)
#2019-05-08 20:54:29
res = time.strftime("%Y-%m-%d %H:%M:%S", (2008, 8, 8, 8, 8, 8, 0, 0, 0))
print(res)
#2008-08-08 08:08:08
日曆calendar模塊
import calendar
print(calendar.isleap(2200))#判斷年份是不是閏年
print(calendar.month(2019, 5))#獲得某年某月的日曆
print(calendar.monthrange(2019, 5))#返回輸入月份的工作日(0-6 ~周一-日)和天数(28-31天)年、月
print(calendar.weekday(2019, 5, 7))#返回輸入日期是周幾

 datatime:可以運算的時間

   当前时间:datetime.datetime.now()

当前时间:datetime.datetime.now()
昨天:datetime.datetime.now() + datetime.timedelta(days=-1)
修改时间:datatime_obj.replace([...])
格式化时间戳:datetime.date.fromtimestamp(timestamp)
sys系統
退出程序,正常退出时exit(0):sys.exit(n)
获取Python解释程序的版本信息:sys.version
最大int值:sys.maxsize | sys.maxint
环境变量:sys.path ******
操作系统平台名称:sys.platform
命令行参数List,第一个元素是程序本身路径:sys.argv
 sys.argv接受所有py文件作为脚本执行外界传入的参数
外界执行传参的方式,cmd中通过python接收器直接执行py文件,python3 py文件 参数们
sys.argv = [py文件绝对路径, 参数1, ..., 参数n]
def copy_file(old, new):
# print("将%s复制成%s" % (old, new))
new_file = os.path.join(new, 'new.py')
with open(old, 'rb') as rf, open(new_file, 'wb') as wf:
for line in rf:
wf.write(line)
if len(sys.argv) == 4:
if sys.argv[1] == 'copy_file':
old = sys.argv[2]
new = sys.argv[3]

if os.path.isfile(old) and os.path.isdir(new):
copy_file(old, new)
os.操作系統
生成单级目录:os.mkdir('dirname')
生成多层目录:os.makedirs('dirname1/.../dirnamen2')
重命名:os.rename("oldname","newname")
工作目录:os.getcwd()
删除文件:os.romeve('file_path')
删除单层空目录:os.rmdir('dirname')
移除多层空目录:os.removedirs('dirname1/.../dirnamen')
列举目录下所有资源:os.listdir('dirname')
路径分隔符:os.sep
行终止符:os.linesep
文件分隔符:os.pathsep
操作系统名:os.name
操作系统环境变量:os.environ
执行shell脚本:os.system()
os.mkdir('abc')  # 在当前文件所在路径下创建abc文件夹
os.mkdir('D:\\abc')  # 就是在指定的绝对路径下创建abc文件夹
os.mkdir('a/b/c')  # a,b必须提前存在,c不能存在
os.makedirs(r'a\b\c')  # a,b存在与否都可以,c不能存在
 

os.path:系统路径操作

执行文件的当前路径:__file__
返回path规范化的绝对路径:os.path.abspath(path)
将path分割成目录和文件名二元组返回:os.path.split(path)
上一级目录:os.path.dirname(path)
最后一级名称:os.path.basename(path)
指定路径是否存在:os.path.exists(path)
是否是绝对路径:os.path.isabs(path)
是否是文件:os.path.isfile(path)
是否是路径:os.path.isdir(path)
路径拼接:os.path.join(path1[, path2[, ...]])
最后存取时间:os.path.getatime(path)
最后修改时间:os.path.getmtime(path)
目标大小:os.path.getsize(path)

random:随机数

print(random.random())#輸出一個0--1之間的隨即小數
print(random.randint(1,10))#輸出1--10隨機整數
print(random.randrange(10,20))#輸出10--20之間隨機一個屬
print(random.uniform(20,30))#輸出20--30之間隨機小數
单例集合随机选择1个:random.choice(item)

单例集合随机选择n个:random.sample(item, n)
洗牌单列集合:random.shuffle(item)

json:序列化

我们把对象(变量)从内存中变成可存储或传输的过程称之为序列化
json语言,就是一种有语法规范的字符串,用来存放数据的,完成各种语言之间的数据交互
1.json語言是{}与[]的组合,{}存放双列信息(类比为字典),[]存放单列信息(类比为列表)
2.{}的key必须是字符串,且必须用""包裹
3.{}与[]中支持的值的类型: dict | list | int | float | bool | null | str
json.dumps()函数的使用,将字典转化为字符串
dict1={'name':'alvin','age':23,'sex':'male'}
json_info = json.dumps(dict1)
print("dict1的类型:"+str(type(dict1)))
print("通过json.dumps()函数处理:")
print("json_info的类型:"+str(type(json_info))
json.loads函数的使用,将字符串转化为字典
json_info = '{"age": "12"}'
dict1 = json.loads(json_info)
print("json_info的类型:"+str(type(json_info)))
print("通过json.dumps()函数处理:")
print("dict1的类型:"+str(type(dict1)))

   json.dump()函数的使用,将json信息写进文件

json_info = "{'age': '12'}"
file = open('1.json','w',encoding='utf-8')
json.dump(json_info,file)
json.load()函数的使用,将读取json信息
file = open('1.json','r',encoding='utf-8')
info = json.load(file)
print(info)

hashlib:加密

不可逆的加密方式沒有解密的方法 md5
解密方式:碰撞解密(不斷組織字符串用同種加密方式加密然後去匹配加密結果)
加密對象:用於傳輸的數據
一次加密
1.後去加密對象 obj=hashlib.md5('')
2.添加加密數據 obj.update(b'...')
3.獲取加密結果 res=hexdigest() ==>return res
加盐加密

  1.保证原数据过于简单,通过复杂的盐也可以提高解密难度
   2.即使被碰撞解密成功,也不能直接识别盐与有效数据

   lock_obj = hashlib.md5()
   lock_obj.update(b'goodgoodstudy')
   lock_obj.update(b'123')
   lock_obj.update(b'daydayup')
                     res = lock_obj.hexdigest() 
   print(res)

hmac

import hmac
# hmac.new(arg) # 必须提供一个参数
cipher = hmac.new('加密的数据'.encode('utf-8'))
print(cipher.hexdigest())

cipher = hmac.new('前盐'.encode('utf-8'))
cipher.update('加密的数据'.encode('utf-8'))
print(cipher.hexdigest())

cipher = hmac.new('加密的数据'.encode('utf-8'))
cipher.update('后盐'.encode('utf-8'))
print(cipher.hexdigest())

cipher = hmac.new('前盐'.encode('utf-8'))
cipher.update('加密的数据'.encode('utf-8'))
cipher.update('后盐'.encode('utf-8'))
print(cipher.hexdigest())

shutil

# 基于路径的文件复制:
shutil.copyfile('source_file', 'target_file')

# 基于流的文件复制:
with open('source_file', 'rb') as r, open('target_file', 'wb') as w:
shutil.copyfileobj(r, w)

# 递归删除目标目录
shutil.rmtree('target_folder')

# 文件移动
shutil.move('old_file', 'new_file')

# 文件夹压缩
# file_name:被压缩后形成的文件名 format:压缩的格式 archive_path:要被压缩的文件夹路径
shutil.make_archive('file_name', 'format', 'archive_path')

# 文件夹解压
# unpack_file:被解压文件 unpack_name:解压后的名字 format解压格式
shutil.unpack_archive('unpack_file', 'unpack_name', 'format')

shelve

# 将序列化文件操作dump与load进行封装
shv_dic = shelve.open("target_file")  # 注:writeback允许序列化的可变类型,可以直接修改值
# 序列化:存
shv_dic['key1'] = 'value1'
shv_dic['key2'] = 'value2'

# 文件这样的释放
shv_dic.close()



shv_dic = shelve.open("target_file", writeback=True)
# 存 可变类型值
shv_dic['info'] = ['原数据']

# 取 可变类型值,并操作可变类型
# 将内容从文件中取出,在内存中添加, 如果操作文件有writeback=True,会将内存操作记录实时同步到文件
shv_dic['info'].append('新数据')

# 反序列化:取
print(shv_dic['info'])  # ['原数据', '新数据']

shv_dic.close()

 







猜你喜欢

转载自www.cnblogs.com/duGD/p/10835125.html
今日推荐