ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

学习Python的第八天

2021-04-13 16:00:52  阅读:119  来源: 互联网

标签:第八天 Python 学习 模块 import print path password os


11. 常见内置模块

什么叫做模块?
import XXXX xxxxx 就是 模块 .py

模块的分类
random math 内置模块

第三方的模块
需要安装
1.在线安装 cmd窗口下通过 pip install 模块名
python -m pip install 模块的名
2.离线安装 下载好所需要的安装包 zip ---- 解压安装包 ------setup.py--------cmd : python install
setup.py
模块导入的问题
import 模块名
在这里插入图片描述
import 模块名 as 别名
在这里插入图片描述
from 包 import 模块的名称
在这里插入图片描述

11.1 random模块

用来产生随机数(伪随机数)
[‘BPF’, ‘LOG4’, ‘NV_MAGICCONST’, ‘RECIP_BPF’, ‘Random’, ‘SG_MAGICCONST’, ‘SystemRandom’,
‘TWOPI’, ‘Sequence’, ‘Set’, ‘all’, ‘builtins’, ‘cached’, ‘doc’, ‘file’, ‘loader’, ‘name’, ‘package’, ‘spec’,
‘accumulate’, ‘acos’, ‘bisect’, ‘ceil’, ‘cos’, ‘e’, ‘exp’, ‘floor’, ‘inst’, ‘log’, ‘os’, ‘pi’, ‘random’, ‘repeat’, ‘sha512’,
‘sin’, ‘sqrt’, ‘test’, ‘test_generator’, ‘urandom’, ‘_warn’, ‘betavariate’, ‘choice’, ‘choices’, ‘expovariate’,
‘gammavariate’, ‘gauss’, ‘getrandbits’, ‘getstate’, ‘lognormvariate’, ‘normalvariate’, ‘paretovariate’,
‘randbytes’, ‘randint’, ‘random’, ‘randrange’, ‘sample’, ‘seed’, ‘setstate’, ‘shuffle’, ‘triangular’,
‘uniform’, ‘vonmisesvariate’, ‘weibullvariate’]

randint() --------- 产生随机整数[m,n]
random() --------------产生0-1的随机数[0,1)
uniform() ------------- 产生正态分布的随机数
randrange() ------ 产生一个范围内的随机数
choices() ---------- 用在序列(容器)(有序的序列)随机筛取一个元素

11.2 math模块

用于数学运算
[‘doc’, ‘loader’, ‘name’, ‘package’, ‘spec’, ‘acos’, ‘acosh’, ‘asin’, ‘asinh’, ‘atan’, ‘atan2’, ‘atanh’,
‘ceil’, ‘comb’, ‘copysign’, ‘cos’, ‘cosh’, ‘degrees’, ‘dist’, ‘e’, ‘erf’, ‘erfc’, ‘exp’, ‘expm1’, ‘fabs’, ‘factorial’,
‘floor’, ‘fmod’, ‘frexp’, ‘fsum’, ‘gamma’, ‘gcd’, ‘hypot’, ‘inf’, ‘isclose’, ‘isfinite’, ‘isinf’, ‘isnan’, ‘isqrt’,
‘lcm’, ‘ldexp’, ‘lgamma’, ‘log’, ‘log10’, ‘log1p’, ‘log2’, ‘modf’, ‘nan’, ‘nextafter’, ‘perm’, ‘pi’, ‘pow’,
‘prod’, ‘radians’, ‘remainder’, ‘sin’, ‘sinh’, ‘sqrt’, ‘tan’, ‘tanh’, ‘tau’, ‘trunc’, ‘ulp’]

ceil ------------- 向上取整
floor ----------- 向下取整
e ------------ 属性 自然常数
fabs ----------- 求绝对值 等价 abs() 全局函数
fmod ----------- 求模运算
isnan -------- 判断是不是数字 (是数字返回 false nan -----not a number)
isfinite ----- 判断是不是无限
pi ----------- 圆周率
pow ------------- 幂次方
sqrt ---------- 平方根

11.3 os模块

操作系统文件
清屏的方法 --------- import os os.system(“cls”)
[‘DirEntry’, ‘F_OK’, ‘GenericAlias’, ‘Mapping’, ‘MutableMapping’, ‘O_APPEND’, ‘O_BINARY’,
‘O_CREAT’, ‘O_EXCL’, ‘O_NOINHERIT’, ‘O_RANDOM’, ‘O_RDONLY’, ‘O_RDWR’, ‘O_SEQUENTIAL’,
‘O_SHORT_LIVED’, ‘O_TEMPORARY’, ‘O_TEXT’, ‘O_TRUNC’, ‘O_WRONLY’, ‘P_DETACH’, ‘P_NOWAIT’,
‘P_NOWAITO’, ‘P_OVERLAY’, ‘P_WAIT’, ‘PathLike’, ‘R_OK’, ‘SEEK_CUR’, ‘SEEK_END’, ‘SEEK_SET’,
‘TMP_MAX’, ‘W_OK’, ‘X_OK’, ‘AddedDllDirectory’, ‘Environ’, ‘all’, ‘builtins’, ‘cached’, ‘doc’, ‘file’,
‘loader’, ‘name’, ‘package’, ‘spec’, ‘check_methods’, ‘execvpe’, ‘exists’, ‘exit’, ‘fspath’,
‘get_exports_list’, ‘walk’, ‘wrap_close’, ‘abc’, ‘abort’, ‘access’, ‘add_dll_directory’, ‘altsep’, ‘chdir’,
‘chmod’, ‘close’, ‘closerange’, ‘cpu_count’, ‘curdir’, ‘defpath’, ‘device_encoding’, ‘devnull’, ‘dup’,
‘dup2’, ‘environ’, ‘error’, ‘execl’, ‘execle’, ‘execlp’, ‘execlpe’, ‘execv’, ‘execve’, ‘execvp’, ‘execvpe’,
‘extsep’, ‘fdopen’, ‘fsdecode’, ‘fsencode’, ‘fspath’, ‘fstat’, ‘fsync’, ‘ftruncate’, ‘get_exec_path’,
‘get_handle_inheritable’, ‘get_inheritable’, ‘get_terminal_size’, ‘getcwd’, ‘getcwdb’, ‘getenv’,
‘getlogin’, ‘getpid’, ‘getppid’, ‘isatty’, ‘kill’, ‘linesep’, ‘link’, ‘listdir’, ‘lseek’, ‘lstat’, ‘makedirs’, ‘mkdir’,
‘name’, ‘open’, ‘pardir’, ‘path’, ‘pathsep’, ‘pipe’, ‘popen’, ‘putenv’, ‘read’, ‘readlink’, ‘remove’,
‘removedirs’, ‘rename’, ‘renames’, ‘replace’, ‘rmdir’, ‘scandir’, ‘sep’, ‘set_handle_inheritable’,
‘set_inheritable’, ‘spawnl’, ‘spawnle’, ‘spawnv’, ‘spawnve’, ‘st’, ‘startfile’, ‘stat’, ‘stat_result’,
‘statvfs_result’, ‘strerror’, ‘supports_bytes_environ’, ‘supports_dir_fd’, ‘supports_effective_ids’,
‘supports_fd’, ‘supports_follow_symlinks’, ‘symlink’, ‘sys’, ‘system’, ‘terminal_size’, ‘times’,
‘times_result’, ‘truncate’, ‘umask’, ‘uname_result’, ‘unlink’, ‘unsetenv’, ‘urandom’, ‘utime’, ‘waitpid’,
‘waitstatus_to_exitcode’, ‘walk’, ‘write’]

chdir() ------- 修改工作目录
在这里插入图片描述

curdir ------- 获取当前的目录 返回的结果的是相对路径 (绝对路径 os.path.abspath(os.curdir) )
chmod() ---------修改权限
close -------- 关闭文件的路径
cpu_count() --------- 返回的cpu的核对应得线程数
getcwd() ----------获取当前路径,返回得是绝对路径,相当linux下pwd
getpid()-------获取当前进程的进程编号
getppid() ------------获取当前进程的父进程的进程编号
kill() ------------- 通过进程编号杀死进程
linesep -------- 属性 对应系统下的换行符
listdir() ------ 返回的对应目录下所有的文件和文件夹(隐藏的文件夹),返回的是列表
makedirs() ----- 创建目录,支持多层目录的创建
mkdir() ----- 创建目录,只能创建一层,不支持多层
open()------创建文件 open()全局函数
pathsep ------- 获取环境变量分隔符 windows ; linux分割符 :
sep --------- 获取路径分割符
remove(文件名或者路径) ----------删除文件
removedirs() --------------- 删除目录,支持多级删除(递归)
system()-------- 执行终端命令

11.4 os.path模块

import os.path
import os.path as p
from os import path
[‘all’, ‘builtins’, ‘cached’, ‘doc’, ‘file’, ‘loader’, ‘name’, ‘package’, ‘spec’, ‘abspath_fallback’,
‘get_bothseps’, ‘getfinalpathname’, ‘getfinalpathname_nonstrict’, ‘getfullpathname’,
‘getvolumepathname’, ‘nt_readlink’, ‘readlink_deep’, ‘abspath’, ‘altsep’, ‘basename’, ‘commonpath’,
‘commonprefix’, ‘curdir’, ‘defpath’, ‘devnull’, ‘dirname’, ‘exists’, ‘expanduser’, ‘expandvars’, ‘extsep’,
‘genericpath’, ‘getatime’, ‘getctime’, ‘getmtime’, ‘getsize’, ‘isabs’, ‘isdir’, ‘isfile’, ‘islink’, ‘ismount’,
‘join’, ‘lexists’, ‘normcase’, ‘normpath’, ‘os’, ‘pardir’, ‘pathsep’, ‘realpath’, ‘relpath’, ‘samefile’,
‘sameopenfile’, ‘samestat’, ‘sep’, ‘split’, ‘splitdrive’, ‘splitext’, ‘stat’, ‘supports_unicode_filenames’,
‘sys’]

abspath(相对路径) ----------------- 返回的路径的所对应的绝对路径
altsep ------------------ 返回的python中的分隔符
basename ------------ 文件名称
dirname ----------- 文件目录
exists ---------------- 判断文件或者目录是否存在
getctime -------- 获取时间(创建时间)
getmtime ------------ 获取修改时间
getsize ------------ 获取文件的大小,单位是字节
isdir-------------- 判断path是否是目录(文件夹)
isfile-------------------判断path是否是文件
isabs ------------- 判断是不是绝对路径
islink ------- 判断是不是链接
ismount ---------- 判断是不是挂载文件
join -------------- 拼接路径
sep ----------- 路径分隔符
split ----------分割路径
relpath ------------- 返回的真正的路径和abspath一样

练习:
需要结合os.path 和 os 模块,以及函数的递归
给出一个路径,遍历当前路径所有文件和文件夹,打印出所有的文件(遇到文件输出路径,如果遇
到的文件夹继续遍历文件夹)
import os from os
import path
#定义一个函数,方法
def scanner_file(url):
#获取当前路径下的所有文件或者文件夹
files = os.listdir(url)
#print(files)
#拼接路径
for f in files:
#real_path = url + “\” + f
real_path = path.join(url,f)
#print(real_path)
#判断是否是文件
if path.isfile(real_path):
print(path.abspath(real_path))
#是目录(文件夹)
elif path.isdir(real_path):
scanner_file(real_path)
#其他情况
else:
print(“其他情况”)
pass
scanner_file(“D:\”)
在这里插入图片描述

11.5 sys模块

[‘breakpointhook’, ‘displayhook’, ‘doc’, ‘excepthook’, ‘interactivehook’, ‘loader’, ‘name’,
‘package’, ‘spec’, ‘stderr’, ‘stdin’, ‘stdout’, ‘unraisablehook’, ‘base_executable’, ‘clear_type_cache’,
‘current_frames’, ‘debugmallocstats’, ‘enablelegacywindowsfsencoding’, ‘framework’, ‘getframe’, ‘git’,
‘home’, ‘xoptions’, ‘addaudithook’, ‘api_version’, ‘argv’, ‘audit’, ‘base_exec_prefix’, ‘base_prefix’,
‘breakpointhook’, ‘builtin_module_names’, ‘byteorder’, ‘call_tracing’, ‘copyright’, ‘displayhook’,
‘dllhandle’, ‘dont_write_bytecode’, ‘exc_info’, ‘excepthook’, ‘exec_prefix’, ‘executable’, ‘exit’, ‘flags’,
‘float_info’, ‘float_repr_style’, ‘get_asyncgen_hooks’, ‘get_coroutine_origin_tracking_depth’,
‘getallocatedblocks’, ‘getdefaultencoding’, ‘getfilesystemencodeerrors’, ‘getfilesystemencoding’,
‘getprofile’, ‘getrecursionlimit’, ‘getrefcount’, ‘getsizeof’, ‘getswitchinterval’, ‘gettrace’,
‘getwindowsversion’, ‘hash_info’, ‘hexversion’, ‘implementation’, ‘int_info’, ‘intern’, ‘is_finalizing’,
‘maxsize’, ‘maxunicode’, ‘meta_path’, ‘modules’, ‘path’, ‘path_hooks’, ‘path_importer_cache’,
‘platform’, ‘platlibdir’, ‘prefix’, ‘ps1’,‘ps2’,‘pycache_prefix’,‘set_asyncgen_hooks’,‘set_coroutine_origin_tracking_depth’, ‘setprofile’, ‘setrecursionlimit’, ‘setswitchinterval’, ‘settrace’,‘stderr’, ‘stdin’, ‘stdout’, ‘thread_info’, ‘unraisablehook’, ‘version’, ‘version_info’, ‘warnoptions’,
‘winver’]

api_version -------------- 属性 获取python内部的版本号
argv --------- 接收脚本参数
copyright ------------ 输出cpython版本号
exit ---------- 退出系统
getdefaultencoding()-------------获取的默认编码,python3默认编码是utf-8
getfilesystemencoding()------------ 获取文件系统的默认编程,默认utf-8
getrecursionlimit()------- 获取python对递归的限制层数
setrecursionlimit() -------------重新设置递归的限制的层数
getrefcount(对象)--------- 获取对象的引用计数,是垃圾回收机制里的引用计数,注意任何对象都
有一个默认引用计数
getwindowsversion() ---------- 获取当前窗口的版本信息
version ------------- 获取版本信息

python的垃圾回收机制:
以引用计数为主,以标记清除和分代收集为辅
Java 以标记清除为主,以引用计数和分代收集为辅

import os from os
import path
import sys
#定义一个函数,方法
def scanner_file(url):
#获取当前路径下的所有文件或者文件夹
files = os.listdir(url)
#print(files)
#拼接路径
for f in files:
#real_path = url + “\” + f
real_path = path.join(url,f)
#print(real_path)
#判断是否是文件
if path.isfile(real_path):
print(path.abspath(real_path))
#是目录(文件夹)
elif path.isdir(real_path):
scanner_file(real_path)
#其他情况
else:
print(“其他情况”)
pass
scanner_file(“D:\”)
ls = sys.argv
#python xxx.py D:// ---------[“xxx.py”,“D://”]
if len(ls) < 2:
print(“对不起,这个脚本参数需要输入,这个脚本参数是要遍历路径”)
else:
scanner_file(sys.argv[1])
在这里插入图片描述
在这里插入图片描述

11.6 加密算法的介绍

有了解加密?加密是计算机中最重要的技术之一
分类:
以算法的是否可逆:
可逆算法
是不是使用同一密钥:
对称加密(解密和加密的时候使用的同一个密钥,DES算法)
不对称加密
加密和解密使用的是同一对密钥(公钥、私钥)https协议 RSA算法

不可逆算法(hash算法)
特点:不可逆、结果是唯一的
MD5

11.6.1 hashlib库

哈希算法
import hashlib
使用步骤
创建算法对象(md5 sha256),返回的是算法对象
md5 = hashlib.md5()
md5
一个字符串加密的话md5 = hashlib.md5(“123”.encode(“utf-8”))
如果不做盐值混淆, md5.hexdigest()
盐值混淆, md5.update(盐值)
在这里插入图片描述
盐值越复杂,加密的安全性就越高

11.6.2 hmac库

也是一个哈希加密库,用到了对称加密
new()
参数:第一个参数是要加密的字符串,第二个参数盐值,第三个参数是加密算法
在这里插入图片描述
首先使用对称加密(密钥就是盐值),得到加密的结果之后又进行了一次hash加密(盐值混淆)

11.7 时间模块

11.7.1 time模块

python提供操作日期和时间的模块

[’_STRUCT_TM_ITEMS’, ‘doc’, ‘loader’, ‘name’, ‘package’, ‘spec’, ‘altzone’, ‘asctime’, ‘ctime’,
‘daylight’, ‘get_clock_info’, ‘gmtime’, ‘localtime’, ‘mktime’, ‘monotonic’, ‘monotonic_ns’,
‘perf_counter’, ‘perf_counter_ns’, ‘process_time’, ‘process_time_ns’, ‘sleep’, ‘strftime’, ‘strptime’,
‘struct_time’, ‘thread_time’, ‘thread_time_ns’, ‘time’, ‘time_ns’, ‘timezone’, ‘tzname’]

asctime() ------------ 获取当前时间
ctime()------ 获取当前时间
localtime()------ 获取的本地时间,返回的是对象
在这里插入图片描述
sleep()-------- 表示休眠的时间,单位秒
time()---------------- 获取当前系统的时间戳,单位也是秒
strftime()------- 将时间对象格式化成字符串
strptime()------将一个特定的时间字符串转换为时间对象

11.7.2 datetime模块

对Time模块的补充
from datetime import datetime
[‘add’, ‘class’, ‘delattr’, ‘dir’, ‘doc’, ‘eq’, ‘format’, ‘ge’, ‘getattribute’, ‘gt’, ‘hash’, ‘init’,
‘init_subclass’, ‘le’, ‘lt’, ‘ne’, ‘new’, ‘radd’, ‘reduce’, ‘reduce_ex’, ‘repr’, ‘rsub’, ‘setattr’, ‘sizeof’,
‘str’, ‘sub’, ‘subclasshook’, ‘astimezone’, ‘combine’, ‘ctime’, ‘date’, ‘day’, ‘dst’, ‘fold’,
‘fromisocalendar’, ‘fromisoformat’, ‘fromordinal’, ‘fromtimestamp’, ‘hour’, ‘isocalendar’,
‘isoformat’, ‘isoweekday’, ‘max’, ‘microsecond’, ‘min’, ‘minute’, ‘month’, ‘now’, ‘replace’, ‘resolution’,
‘second’, ‘strftime’, ‘strptime’, ‘time’, ‘timestamp’, ‘timetuple’, ‘timetz’, ‘today’, ‘toordinal’, ‘tzinfo’,
‘tzname’, ‘utcfromtimestamp’, ‘utcnow’, ‘utcoffset’, ‘utctimetuple’, ‘weekday’, ‘year’]

now() ------------获取当前的时间

11.7.3 其他模块

日历的模块(calendar)
uuid 模块 ------------ 一般会用在文件上传或者文件备份的时候
产生一个永不重复的字符串
uuid.uuid4().hex

练习:
完成用户注册登录的案例
import sys
import hashlib
users=[]

#登录界面
def main():
print("*~“22)
print(‘1.用户注册’.center(40))
print(‘2.用户登录’.center(40))
print(‘3.退出系统’.center(40))
print("
~”*22)
choice=input(“请输入你的选择:”)
return choice

def password_md5(password):
md = hashlib.md5()
#盐值混淆
md.update(‘acawacadw’.encode(‘utf-8’))
return md.hexdigest()

#注册registered
def registered():
username=input(‘请输入用户名:’)
password=input(‘请输入密码:’)
#数据校验
#用户名不能为空
if username == None or username.strip() == '"":
print(‘用户名不能为空’)
return
if password == None or password == ‘’ or len(password)<6:
print(‘密码不能为空或长度不能小于6位’)
return
for i in users:
if i.get(‘username’)==username:
print(‘用户名重复’)
return
#创建字典对象
user={}
user[‘username’]=username
# user[‘password’]=password
user[‘password’]=password_md5(password)
print(user)
users.append(user)
print(users)

#登录
def login():
username=input(‘请输入用户名:’)
password=input(‘请输入密码:’)
is_login(username,password_md5(password))
# for i in users:
# if i.get(‘username’)==username and i.get(‘password’)==password:
# print(‘登录成功’)
# return
# if is_login(username,password):
# print(‘恭喜你,登陆成功’)
# else:
# print(‘抱歉,登录失败’)

def is_login(username,password):
for i in users:
if i.get(‘username’)==username and i.get(‘password’)==password:
print(‘登录成功’)
return True

while True:
choice=main()
if choice==‘1’:
registered()
elif choice==‘2’:
login()
else:
print(‘退出系统’)
sys.exit()
在这里插入图片描述
在这里插入图片描述

标签:第八天,Python,学习,模块,import,print,path,password,os
来源: https://blog.csdn.net/weixin_53002381/article/details/115668273

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有