一、加密模块

1、有解密的加密方式(base64)

#base64加密
import base64
str_encrypt = input("输入要加密的字符串:\n")
base64_encrypt = base64.b64encode(str_encrypt.encode('utf-8'))
print("BASE64加密串:\n"+str(base64_encrypt,'utf-8'))

# 解密
str_decrypt = input("输入要解密的字符串:\n")
base64_decrypt = base64.b64decode(str_decrypt.encode('utf8'))
print("BASE64解密串:\n"+str(base64_decrypt,'utf-8'))

2、无解密的加密方式hashlib(碰撞检查)

1、不同数据加密后的结果一定不一致

2、相同数据的加密结果一定是一致的

import hashlib

user_map = {}
# user_map = {'abc': '202cb962ac59075b964b07152d234b70'}
def lock(msg):
    b_msg = msg.encode('utf-8')
    # 将数据进行加密
    cipher = hashlib.md5(b_msg)
    # 拿到加密后的字符串
    return cipher.hexdigest()

def register():
    print('注册...')
    user = input('user: ')
    pwd = input('pwd: ')
    lock_pwd = lock(pwd)
    # print(user)
    # print(lock_pwd)
    user_map[user] = lock_pwd
    print(user_map)

register()

def loging():
    print('登录...')
    user = input('user: ')
    pwd = input('pwd: ')
    if user in user_map:
        lock_pwd = lock(pwd)
        if user_map[user] == lock_pwd:
            print('登录成功')
        else:
            print('登录失败')
    else:
        print('账号不存在')
loging()

三种方式:

2.1、直接传参

# part1
cipher = hashlib.md5('要被加密的字符串'.encode('utf-8'))
print(cipher.hexdigest())

cipher = hashlib.md5('要被加密的字符串'.encode('utf-8'))
print(cipher.hexdigest())
# 整体被加密的数据一样,加密后的结果就一样
cipher = hashlib.md5('要被加密'.encode('utf-8'))
cipher.update('的字'.encode('utf-8'))
cipher.update('符串'.encode('utf-8'))
print(cipher.hexdigest())

2.2、加盐

# part2:加盐 - add salt
cipher = hashlib.md5()
msg = input('msg:')
# 加前盐:最好与要加密的数据类型一致
cipher.update('前盐'.encode('utf-8'))
# 要被加密的数据
cipher.update(msg.encode('utf-8'))
# 加后盐
cipher.update('后盐'.encode('utf-8'))
print(cipher.hexdigest())

print(hashlib.md5('前盐123后盐'.encode('utf-8')).hexdigest())

2.3、加密长度不一样

# part3:加密长度不一样
cipher = hashlib.sha3_512('abc123呵呵'.encode('utf-8'))
print(cipher.hexdigest())

3、hmac模块

和md5()区别:

 hashlib.md5():

      -- 可以有初始参数,可以没有初始参数

      -- 可以通过update再添加新内容

 hmac.new():

      -- 必须有初始参数

      -- 可以通过update再添加新内容

import hmac

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

二、ini配置文件操作模块

# my.ini文件
[server]
name = mysql
version = 20000

[client]
name = owen
adress = 192.168.11.174

操作文件的代码

from configparser import ConfigParser
# 初始化配置文件的操作对象
parser = ConfigParser()
# 读
parser.read('my.ini', encoding='utf-8')
# 大分类:section
print(parser.sections())
# 某分类下的keys:option
print(parser.options('server'))
print(parser.options('client'))
for section in parser.sections():
    print(parser.options(section))
# 获取某section下某option的具体值
res = parser.get('server', 'version')
# res = parser.getfloat('server', 'version')
print(res, type(res))

# 写
parser.set('server', 'version', '20000')  # 写到内存
parser.write(open('my.ini', 'wt'))

三、shell指令操作模块

import subprocess

# subprocess.run('dir', shell=True)

order = subprocess.Popen('dir1',
                         shell=True,
                         # 存放指令执行成功的信息管道
                         stdout=subprocess.PIPE,
                         # 存放指令执行失败的信息管道
                         stderr=subprocess.PIPE
                         )
print(order.stdout)
success_msg = order.stdout.read().decode('GBK')
print(success_msg)
error_msg = order.stderr.read().decode('GBK')
print(error_msg)
# 实际项目中,会接着对success_msg加以分析处理

order = subprocess.run('dir',
                       shell=True,
                       # 存放指令执行成功的信息管道
                       stdout=subprocess.PIPE,
                       # 存放指令执行失败的信息管道
                       stderr=subprocess.PIPE
                       )
print(order.stdout)
success_msg = order.stdout.decode('GBK')
print(success_msg)
error_msg = order.stderr.decode('GBK')
print(error_msg)

四、excel操作模块

import xlrd
# 将excel文件读成对象
workbook = xlrd.open_workbook('寂寞.xlsx')
# 获取所有所有表格名称
# print(workbook.sheet_names())
# 选取一个表
sheet = workbook.sheet_by_index(0)
# print(sheet.name, sheet.nrows, sheet.ncols)
# 整行整列信息
print(sheet.row(1))
print(sheet.col(0))
# 单元格
print(sheet.cell(13, 4))
print(sheet.cell(13, 4).ctype)
print(sheet.cell(13, 4).value)
print(sheet.row(13)[4])

# 时间
info = sheet.cell(2, 0).value
print(info)
info = xlrd.xldate_as_datetime(info, 0)
print(info)

import xlwt
# 创建工作簿
work = xlwt.Workbook()
# 创建一个表
sheet = work.add_sheet("求败")

# 创建一个字体对象
font = xlwt.Font()
font.name = "Times New Roman"  # 字体名称
font.bold = True  # 加粗
font.italic = True  # 斜体
font.underline = True  # 下划线
# 创建一个样式对象
style = xlwt.XFStyle()
style.font = font

keys = ['Owen', 'Zero', 'Egon', 'Liuxx', 'Yhh']
# # 写入标题
for k in keys:
    # sheet.write(0, keys.index(k), k, style)
    sheet.write(keys.index(k) + 2, 1, k, style)
# # 写入数据
# sheet.write(1, 0, 'cool', style)

# 保存至文件
work.save("孤独.xlsx")

五、xml模块

xml文件:

<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2018</year>
        <gdppc>141100</gdppc>
        <neighbor direction="E" name="Austria" />
        <neighbor direction="W" name="Switzerland" />
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor direction="N" name="Malaysia" />
    </country>
    <country name="Panama">
        <rank updated="yes">69</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor direction="W" name="Costa Rica" />
        <neighbor direction="E" name="Colombia" />
    </country>
</data>

python操作

import xml.etree.ElementTree as ET

tree = ET.parse('my.xml')
# 根节点
root_ele = tree.getroot()
print(root_ele.tag)

# 遍历根节点
for ele in root_ele:
    # print(ele)
    # print(ele.attrib)
    # print(ele.attrib['name'])
    if ele.attrib['name'] == 'Liechtenstein':
        for e in ele:
            print(e.text)

print(list(root_ele.iter('year'))[0].text)
print(root_ele.find('country'))
print(root_ele.findall('country'))

# 修改
list(root_ele.iter('year'))[0].text = '2018'
tree.write('my.xml')

# 增
my_ele = ET.Element('MyEle')
my_ele.text = 'new_ele'
my_ele.attrib = {'name': 'my_ele'}
root_ele.append(my_ele)
tree.write('my.xml')

# 删
my_ele = root_ele.find('MyEle')
# print(my_ele)
root_ele.remove(my_ele)
tree.write('my.xml')

六、数据格式分类

# xml | json

import json
# json.dumps() json.dump()
# json.loads() json.loads()

json:json就是一种特殊格式的字符串
# 格式要求:
1.只能由{}和[]嵌套形成
2.只能有一个根: 最外层要么是{}(推荐),要么是[]
3.所以key都是字符串类型,且json字符串中所有字符串类型必须用""包裹
4.json字符串中value类型可以为: number | boolean | null | 字符串 | dic | list
dic = {'': [1, 3.14, True, None, "字符串"]}
print(json.dumps(dic))

j_str = """{"key": [1, 3.14, true, null, "字符串"]}"""
print(json.loads(j_str))

'''
{
    "info": [1, 2, 3, 4, 5]
}
'''

# xml格式数据:
1.xml文件中都是由自定义标签嵌套形成,区分大小写
2.只能有一个根标签:其他内容或标签都被该标签包裹
3.标签名为key,标签中的值为value
4.与json不同的是,xml标签可以额外添加属性来标识key的区分度

python基础——15(加密、excel操作、ini文件操作、xml操作模块及数据格式分类)的更多相关文章

  1. 关于C#操作INI文件的总结

    原文:关于C#操作INI文件的总结   INI文件其实是一种具有特定结构的文本文件,它的构成分为三部分,结构如下: [Section1]key 1 = value2key 1 = value2--[S ...

  2. 十五. Python基础(15)--内置函数-1

    十五. Python基础(15)--内置函数-1 1 ● eval(), exec(), compile() 执行字符串数据类型的python代码 检测#import os 'import' in c ...

  3. python基础 实战作业 ---Excel基本读写与数据处理

    代码地址如下:http://www.demodashi.com/demo/11650.html 看完本篇需要: 10min 作业练习需要: 0.5h~3h(依练习者对python熟悉程度而定) 看完本 ...

  4. INI 文件的读写操作

    在C#中对INI文件进行读写操作,在此要引入using System.Runtime.InteropServices; 命名空间,具体方法如下: #region 变量 private static r ...

  5. .net操作InI文件

    public class INI { public static string IniFileName = "";//路径 [DllImport("kernel32&qu ...

  6. C#利用Vini.cs操作INI文件

    VClassLib-CS项目Github地址:https://github.com/velscode/VClassLib-CS VINI文档地址:https://github.com/velscode ...

  7. [转]C#操作INI文件

    在很多的程序中,我们都会看到有以.ini为后缀名的文件,这个文件可以很方便的对程序配置的一些信息进行设置和读取,比如说我们在做一个程序后台登陆的时候,需要自动登录或者是远程配置数据库连接,及保存密码设 ...

  8. QSettings配置读写-win注册表操作-ini文件读写

    版权声明:若无来源注明,Techie亮博客文章均为原创. 转载请以链接形式标明本文标题和地址: 本文标题:QSettings配置读写-win注册表操作-ini文件读写     本文地址:http:// ...

  9. C#操作INI文件(明天陪你看海)

    C#操作INI文件 在很多的程序中,我们都会看到有以.ini为后缀名的文件,这个文件可以很方便的对程序配置的一些信息进行设置和读取,比如说我们在做一个程序后台登陆的时候,需要自动登录或者是远程配置数据 ...

随机推荐

  1. 阿里云ECS基础知识01

  2. IIS7开启目录浏览功能

    IIS7开启目录浏览功能: 在右侧操作中点击启用,并在左侧面板中勾选显示字段.

  3. tera term超级终端

    一款Window上的虚拟终端工具,它同时支持串口连接和网络连接,而对于网络连接它支持Telnet和SSH协议.最关键的是Tera Term支持自己的脚本语言,即TTL(Tera Term Langua ...

  4. Excel2Json记录

    1.有关配置的读取 import configparser import codecs #配置文件格式[config] #自定义的配置key=valuekey2=value2 读取配置 conf = ...

  5. vue2.0:(一)、vue的安装和项目搭建(以外卖app项目举例)

    vue系列踩坑大作战由此就要开始了,准备好了吗,和我一起踩坑,学会vue吧.同时,也欢迎大家把自己遇到的坑发出来,让更多的人学会vue,因为我深知前端学习新框架不容易,尤其是我这种半路出家的女前端.不 ...

  6. mac系统连接Android手机

    1. 打开终端,输入:system_profiler SPUSBDataType,查看Mac系统所有USB设备信息,找到相应的厂商Vender ID 2.输入echo "Vender ID& ...

  7. 双飞翼布局介绍-始于淘宝UED-2011年淘宝玉伯写的

    仔细分析各种布局的技术实现,可以发现下面三种技术被经常使用: 浮动 float 负边距 negative margin 相对定位 relative position 这是实现布局的三个最基本的原子技术 ...

  8. Oracle Flashback Technology【闪回技术】

    -------------------------与其他数据库相比,Oracle的闪回让开发者多了一条选择的路. Flashback的目的 先看下Oracle官方文档中的解释: Oracle Flas ...

  9. MVC 学习小总结

    一般情况下新增字段首选现在数据库更新,然后再从数据库更新模型 第二选择是从模板添加字段更新数据库(面临删除所有数据可能,慎用) 第三是没有T4模板的前提下再模型完成操作然后修改model类防止mode ...

  10. vue的使用-项目总结

    1,这是一个重前端逻辑,轻交互,数据展示的项目,可读性差,2,组件划分的坑,复用过多的坑,复用过多导致要在js手动判断太多东西,不便于可读3,vuex的坑,数据分为后台请求数据的暂存,前端页面逻辑的状 ...