第17天 hash模块 subprocess模块 os模块 sys模块 configparser模块

模块的应用场景:
hash模块:主要应用于文件加密或者校验文件的完整性
subprocess:主要用来运行操作系统命令,导入subprocess可以理解成导入cmd
os模块:主要应用于环境变量,文件目录
sys:主要记住sys.path,sys.argv
configparser:读取修改固定格式的配置文件,配置文件的后缀是ini或者cnf

hash算法的三大特点
如果传入一段内容,会得到一串hash值,hash值有三大特点
1.如果传入的内容与采用的算法一样,那么得到的hash值一定一样
2.只有采用的算法是固定的,hash值的长度是固定的,不会随着内容的增长而变长
3.hash值不可逆,不能通过hash值反解出内容是什么
1+2==>可以用来校验文件的完整性
1+3==>可以用来加密
注意:往hash工厂里面传值,必须传bytes类型的值
在这里插入图片描述
用hash算法得到hash值

import hashlib

m = hashlib.md5()  # md5是最简单的一种hash算法,调用md5会得到一个返回值,m就是hash工厂(还有一些其他的算法,比如512算法会让hash值的复杂程度变高)
m.update("你好".encode("utf-8"))     #往hash工厂m里面传值
m.update("nana".encode("utf-8"))
m.update("哈哈".encode("utf-8"))
# 以上传输方式是分批次md5里面传值,传值的结果是:你好nana哈哈

print(m.hexdigest())        #最后得到的hash值:118d65c2111c3c6c357f2041403fccca

用hash算法校验文件的完整性

import hashlib

m = hashlib.md5()
with open(r"D:\pycharm文件\test\practice\c.txt", mode="rb")as f:
    for line in f:
        m.update(line)
    res = m.hexdigest()
    print(res)        # 把hash值和文件一起传给客户端,hash值为:c2ad1c51f02542950e58666460070f2f

用hash算法加密文件

import hashlib

m = hashlib.md5()
password = "123nana"
m.update(password.encode("utf-8"))
m.update("娜娜".encode("utf-8"))
print(m.hexdigest())

subprocess模块

subprocess主要用来运行操作系统命令,导入subprocess可以理解成导入windows系统的cmd

import subprocess
import time

obj = subprocess.Popen("tasklist",  # subprocess.Popen开启了一个子进程,sleep后才再pycharm显示结果是因为两个进程共用一个终端
                       shell=True,
                       stdout=subprocess.PIPE,  # 两个进程之间的内存空间是不共享的,主进程想取子进程的结果,使用“管道”可以实现内存共享
                       stderr=subprocess.PIPE
                       )

# time.sleep(3)

stdout_res = obj.stdout.read()  # 该管道调正确的结果
stderr_res = obj.stderr.read()  # 该管道调错误的结果

print(stdout_res.decode("gbk"))  # windows系统解码时gbk格式

os模块

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.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不存在,返回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的大小

import os

print(os.getcwd())
os.environ["name"] = "nana"         #存储成字典类型,导入os模块直接使用,可以规避循环导入模块的问题
print(os.environ["name"])

os模块path功能的使用
print(os.path.abspath(r"a.txt"))  # 相对路径转成绝对路径  #D:\pycharm文件\test\practice\a.txt
print(os.path.split(r"D:\pycharm文件\test\practice\a.txt"))  # ('D:\\pycharm文件\\test\\practice', 'a.txt')
print(os.path.dirname(r"D:\pycharm文件\test\practice\a.txt"))  # D:\pycharm文件\test\practice
print(os.path.basename(r"D:\pycharm文件\test\practice\a.txt"))  # a.txt
print(os.path.exists(r"D:\pycharm文件\test\practice\a.txt"))   #如果path存在,返回True;如果path不存在,返回False
print(os.path.isabs(r"D:\pycharm文件\test\practice\a.txt"))  # 如果path是绝对路径,返回True
print(os.path.isfile(r"D:\pycharm文件\test\practice\a.txt"))  # 如果path是一个存在的文件,返回True。否则返回False
print(os.path.isdir(r"D:\pycharm文件\test\practice\a.txt"))  # 如果path是一个存在的目录,则返回True。否则返回False
print(os.path.join("D", "a", "b", "c"))    #帮忙拼接路径D\a\b\c
print(os.path.getatime(r"D:\pycharm文件\test\practice\a.txt"))  # 返回path所指向的文件或者目录的最后存取时间
print(os.path.getatime(r"D:\pycharm文件\test\practice\a.txt"))  # 返回path所指向的文件或者目录的最后修改时间
print(os.path.getsize(r"D:\pycharm文件\test\practice\a.txt"))  # 返回path的大小

sys模块

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

用sys.argv实现拷贝终端的文件内容
import sys

scr_file = sys.argv[1]  # 原文件
dst_file = sys.argv[2]  # 目标文件
with open(r"%s" % scr_file, mode="rb")as f1, \
        open(r"%s" % dst_file, mode="wb")as f2:
    for line in f1:
        f2.write(line)

configparser模块
读取修改固定格式的配置文件,配置文件的后缀是ini或者cnf

读取
import configparser

config = configparser.ConfigParser()
config.read('a.cfg')

# 查看所有的标题
res = config.sections()  # ['section1', 'section2']
print(res)

# 查看标题section1下所有key=value的key
options = config.options('section1')
print(options)  # ['k1', 'k2', 'user', 'age', 'is_admin', 'salary']

# 查看标题section1下所有key=value的(key,value)格式
item_list = config.items('section1')
print(item_list)  # [('k1', 'v1'), ('k2', 'v2'), ('user', 'egon'), ('age', '18'), ('is_admin', 'true'), ('salary', '31')]

# 查看标题section1下user的值=>字符串格式
val = config.get('section1', 'user')
print(val)  # egon

# 查看标题section1下age的值=>整数格式
val1 = config.getint('section1', 'age')
print(val1)  # 18

# 查看标题section1下is_admin的值=>布尔值格式
val2 = config.getboolean('section1', 'is_admin')
print(val2)  # True

# 查看标题section1下salary的值=>浮点型格式
val3 = config.getfloat('section1', 'salary')
print(val3)  # 31.0
改写
import configparser

config = configparser.ConfigParser()
config.read('a.cfg', encoding='utf-8')

# 删除整个标题section2
config.remove_section('section2')

# 删除标题section1下的某个k1和k2
config.remove_option('section1', 'k1')
config.remove_option('section1', 'k2')

# 判断是否存在某个标题
print(config.has_section('section1'))

# 判断标题section1下是否有user
print(config.has_option('section1', ''))

# 添加一个标题
config.add_section('egon')

# 在标题egon下添加name=egon,age=18的配置
config.set('egon', 'name', 'egon')
config.set('egon', 'age', 18)  # 报错,必须是字符串

# 最后将修改的内容写入文件,完成最终的修改
config.write(open('a.cfg', 'w'))

猜你喜欢

转载自blog.csdn.net/Yosigo_/article/details/112319648