分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 软件开发

6 - 常用模块(os,sys,time&datetime,random,json&picle,shelve,hashlib)

发布时间:2023-09-06 01:42责任编辑:郭大石关键词:jsjson

导入模块

想使用 Python 源文件,只需在另一个源文件里执行 import 语句

import module1[, module2[,... moduleN]

from语句让你从模块中导入一个指定的部分到当前命名空间中

from modname import name1[, name2[, ... nameN]]
内置的函数 dir() 可以找到模块内定义的所有名称。以一个字符串列表的形式返回
>>> import sys>>> dir(sys)[‘__displayhook__‘, ‘__doc__‘, ‘__excepthook__‘, ‘__interactivehook__‘, ‘__loader__‘, ‘__name__‘, ‘__package__‘, ‘__spec__‘, ‘__stderr__‘, ‘__stdin__‘, ‘__stdout__‘, ‘_clear_type_cache‘, ‘_current_frames‘, ‘_debugmallocstats‘, ‘_enablelegacywindowsfsencoding‘, ‘_getframe‘, ‘_git‘, ‘_home‘, ‘_xoptions‘, ‘api_version‘, ‘argv‘, ‘base_exec_prefix‘, ‘base_prefix‘, ‘builtin_module_names‘, ‘byteorder‘, ‘call_tracing‘, ‘callstats‘, ‘copyright‘, ‘displayhook‘, ‘dllhandle‘, ‘dont_write_bytecode‘, ‘exc_info‘, ‘excepthook‘, ‘exec_prefix‘, ‘executable‘, ‘exit‘, ‘flags‘, ‘float_info‘, ‘float_repr_style‘, ‘get_asyncgen_hooks‘, ‘get_coroutine_wrapper‘, ‘getallocatedblocks‘, ‘getcheckinterval‘, ‘getdefaultencoding‘, ‘getfilesystemencodeerrors‘, ‘getfilesystemencoding‘, ‘getprofile‘, ‘getrecursionlimit‘, ‘getrefcount‘, ‘getsizeof‘, ‘getswitchinterval‘, ‘gettrace‘, ‘getwindowsversion‘, ‘hash_info‘, ‘hexversion‘, ‘implementation‘, ‘int_info‘, ‘intern‘, ‘is_finalizing‘, ‘last_traceback‘, ‘last_type‘, ‘last_value‘, ‘maxsize‘, ‘maxunicode‘, ‘meta_path‘, ‘modules‘, ‘path‘, ‘path_hooks‘, ‘path_importer_cache‘, ‘platform‘, ‘prefix‘, ‘set_asyncgen_hooks‘, ‘set_coroutine_wrapper‘, ‘setcheckinterval‘, ‘setprofile‘, ‘setrecursionlimit‘, ‘setswitchinterval‘, ‘settrace‘, ‘stderr‘, ‘stdin‘, ‘stdout‘, ‘thread_info‘, ‘version‘, ‘version_info‘, ‘warnoptions‘, ‘winver‘]

__name__属性

一个模块被另一个程序第一次引入时,其主程序将运行。如果我们想在模块被引入时,模块中的某一程序块不执行,我们可以用__name__属性来使该程序块仅在该模块自身运行时执行。

if __name__ == ‘__main__‘: ??print(‘程序自身在运行‘)else: ??print(‘被另一模块调用模块‘)

OS模块 

提供对操作系统进行调用的接口

os.getcwd() ?????????????#获取当前工作目录,即当前python脚本工作的目录路径os.chdir("dirname") ?????#改变当前脚本工作目录;相当于shell下cdos.curdir ???????????????#返回当前目录: (‘.‘)os.pardir ???????????????#获取当前目录的父目录字符串名:(‘..‘)os.makedirs(‘dirname1/dirname2‘) ???#可生成多层递归目录os.removedirs(‘dirname1‘)#若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推os.mkdir(‘dirname‘) ?????#生成单级目录;相当于shell中mkdir dirnameos.rmdir(‘dirname‘) ?????#删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirnameos.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 ??????????????#输出用于分割文件路径的字符串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不存在,返回Falseos.path.isabs(path) ?????#如果path是绝对路径,返回Trueos.path.isfile(path) ????#如果path是一个存在的文件,返回True。否则返回Falseos.path.isdir(path) ?????#如果path是一个存在的目录,则返回True。否则返回Falseos.path.join(path1[, path2[, ...]]) ?#将多个路径组合后返回,第一个绝对路径之前的参数将被忽略os.path.getatime(path) ??#返回path所指向的文件或者目录的最后存取时间os.path.getmtime(path) ??#返回path所指向的文件或者目录的最后修改时间

sys模块

sys.argv ???????????????#可以在后面添加参数用sys.argv[x]来获取sys.exit(n) ????????????#退出程序,正常退出时exit(0)sys.version ????????????#获取Python解释程序的版本信息sys.maxint ?????????????#最大的Int值sys.path ???????????????#返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值sys.platform ???????????#返回操作系统平台名称sys.stdout.write(‘please:‘) #屏幕打印please

time & datetime模块

import timeprint(time.time()) ???????#当前时间搓print(time.localtime()) ??#当前时间的struct_timeprint(time.altzone) ?#返回与utc时间的时间差,以秒计算print(time.asctime()) #返回时间格式"Mon Feb 12 00:27:57 2018",print(time.gmtime(time.time()-800000)) #返回utc时间的struc时间对象格式# 日期字符串 转成 ?时间戳time_struct = time.strptime("2016/05/22","%Y/%m/%d") #将日期字符串转成struct时间对象格式stamp = time.mktime(time_struct) #将struct时间对象转成时间戳#将时间戳转为字符串格式print(time.gmtime(time.time() - 86640)) ?# 将utc时间戳转换成struct_time格式print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将utc struct_time格式转成指定的字符串格式x = time.localtime(11111) #设置时间print(x.tm_year,x.tm_yday)#打印年和日print(time.mktime(x)) ????#打印时间#格式化打印print(time.strftime(‘%Y-%m-%d %H:%M:%S‘,x))print(time.asctime(x))print(time.strptime("2016/05/22","%Y/%m/%d"))"""%a ???本地(locale)简化星期名称 ???%A ???本地完整星期名称 ???%b ???本地简化月份名称 ???%B ???本地完整月份名称 ???%c ???本地相应的日期和时间表示 ???%d ???一个月中的第几天(01 - 31) ???%H ???一天中的第几个小时(24小时制,00 - 23) ???%I ???第几个小时(12小时制,01 - 12) ???%j ???一年中的第几天(001 - 366) ???%m ???月份(01 - 12) ???%M ???分钟数(00 - 59) ???%p ???本地am或者pm的相应符 ???一 ???%S ???秒(01 - 61) ???二 ???%U ???一年中的星期数。(00 - 53星期天是一个星期的开始。)第一个星期天之前的所有天数都放在第0周。 ???三 ???%w ???一个星期中的第几天(0 - 6,0是星期天) ???三 ???%W ???和%U基本相同,不同的是%W以星期一为一个星期的开始。 ???%x ???本地相应日期 ???%X ???本地相应时间 ???%y ???去掉世纪的年份(00 - 99) ???%Y ???完整的年份 ???%Z ???时区的名字(如果不存在为空字符) ???%% ???‘%’字符"""import datetimeprint(datetime.date.fromtimestamp(time.time()) ) ??????#时间戳直接转成日期格式 2016-08-19print(datetime.datetime.now()) ????????????????????????#当前时间print(datetime.datetime.now() + datetime.timedelta(3)) #当前时间+3天print(datetime.datetime.now().replace(hour=23)) 

random模块

import randomprint(random.random()) ????????????????#用于生成一个0到1的随机符点数:print (random.randint(1,7)) ???????????#随机生成1-7之间的数print (random.randrange(1,10,2)) ??????#随机生成0-9直接的奇数print(random.choice(‘罗毅,张驿‘)) ?????#随机生成一个元素print(random.choice([‘周思益‘,‘张驿‘,‘文艺‘,‘罗毅‘,‘林毅‘]))#随机生成一个名字print(random.sample([1,2,3,4,5],3)) ???#随机获取指定长度的片段

json & pickle 模块

用于序列化的两个模块

  • json,用于字符串 和 python数据类型间进行转换
  • pickle,用于python特有的类型 和 python的数据类型间进行转换
import jsondata1 = { ???‘name‘ : ‘刘瑶‘, ???‘age‘ ?: ?17, ???‘post‘ ?: ‘student‘}json_str = json.dumps(data1)print ("Python数据:", repr(data1))
print ("JSON对象:", json_str)
data2 = json.loads(json_str)print ("data2[‘name‘]: ", data2[‘name‘])print ("data2[‘age‘]: ", data2[‘age‘])"""运行结果:Python数据: {‘name‘: ‘刘瑶‘, ‘age‘: 17, ‘post‘: ‘student‘}JSON对象: {"name": "\u5218\u7476", "age": 17, "post": "student"}data2[‘name‘]: ?刘瑶data2[‘age‘]: ?17"""

json写入文件

# 写入 JSON 数据with open(‘data.json‘, ‘w‘) as f: ???json.dump(data, f) #f.write(json.dumps(data))效果一样# 读取数据with open(‘data.json‘, ‘r‘) as f: ???data = json.load(f.read())

如果你要处理的是文件而不是字符串,你可以使用 json.dump() 和 json.load() 来编码和解码JSON数据

# 写入 JSON 数据with open(‘data.json‘, ‘w‘) as f: ???json.dump(data, f)# 读取数据with open(‘data.json‘, ‘r‘) as f: ???data = json.load(f)

shelve 模块

shelve模块是一个简单的k,v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据格式

import pickledef abc(a): ???print(‘aaaa‘,a)data0 = { ???‘name‘:‘易俊杰‘, ???‘age‘:17, ???‘post‘:‘student‘, ???‘imformation‘:abc}#写入文件1f = open(‘data.txt‘,‘wb‘)pickle.dump(data0,f) #f.write(pickle.dumps(data))f.close()#读文件1f = open(‘data.txt‘,‘rb‘)data3 = pickle.load(f) ?#data2 = json.loads(f.read())print(data3[‘age‘])data3[‘imformation‘](‘a‘)f.close()#写入文件2class Text(object): ???def __init__(self,n): ???????self.n = nd = shelve.open(‘shelve_txt‘)d[‘text‘] = Text(‘刘思明‘)d[‘name‘] = [‘谭佩瑶‘,‘陈贵龙‘,‘刘瑶‘]d.close()#读文件2d2 = shelve.open(‘shelve_txt‘)print(d2.get(‘text‘).n)for k in d2: ???print(k,d2[k])d2.close()

hashlib模块 

用于加密相关的操作,3.x里代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法。

import hashlib# ######## md5 ########hash = hashlib.md5()hash.update(b‘root‘)print(hash.hexdigest())# ######## sha1 ########hash = hashlib.sha1()hash.update(b‘root‘)print(hash.hexdigest())# ######## sha256 ########hash = hashlib.sha256()hash.update(b‘root‘)print(hash.hexdigest())# ######## sha384 ########hash = hashlib.sha384()hash.update(b‘root‘)print(hash.hexdigest())# ######## sha512 ########hash = hashlib.sha512()hash.update(b‘root‘)print(hash.hexdigest())

6 - 常用模块(os,sys,time&datetime,random,json&picle,shelve,hashlib)

原文地址:https://www.cnblogs.com/StringSir/p/8443548.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved