一、加密模块

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. hibernate Day2 笔记

    1.主键生成策略 <!--映射配置文件 >映射配置文件名称和位置没法有固定要求 >映射配置文件中的name属性值写实体类相关内容 -- class 标签name属性值实体类全路径 - ...

  2. web移动端滑动插件

    1.slip只有6.3k可以说是非常小了,主要是通过css3里面的transform来改变的位置,控制的是父容器,使用也非常简单,具体信息移步slip.js.一个简单的demo如下 <!DOCT ...

  3. 05.Javascript——入门函数

    //定义函数的方法1 function abs(x) { if (x >= 0) { return x; } else { return -x; } } 上述abs()函数的定义如下: func ...

  4. arcengine 将地图文件保存为图片(包括各种图片格式)

    1,最近做了个地图文件输出图片的功能,思想主要就是利用MapControl的ActiveView中的out方法: 2代码如下:欢迎交流指正 SaveFileDialog m_save = new Sa ...

  5. laravel 错误总结

    1.ReflectionException (-1) Class PhotosController does not exist 原因: 资源路由的问题 ,命名空间要区分大小写,admin首字母要大写 ...

  6. puppeteer 中国区的使用

    puppeteer 中国区的使用 [issues]https://github.com/GoogleChrome/puppeteer/issues/1426 两种方案 使用 cnpm .npmrc 中 ...

  7. SqlServer表和excel数据批量复制方法

    SqlServer表和excel数据批量复制方法 一.SqlServer表数据复制到excel方法: 1.新建查询,用sql语句把表数据读出来 2.然后,选择数据,右键“复制”(如果需要表字段名称,则 ...

  8. ipsec配置strongswan.conf和ipsec.conf

    配置strongswan.conf vi /usr/local/etc/strongswan.conf # strongswan.conf - strongSwan configuration fil ...

  9. JavaScript中valueOf函数与toString方法

    基本上,所有JS数据类型都拥有valueOf和toString这两个方法,null除外.它们俩解决javascript值运算与显示的问题,本文将详细介绍,有需要的朋友可以参考下   JavaScrip ...

  10. Codeforces Round #271 (Div. 2)-A. Keyboard

    http://codeforces.com/problemset/problem/474/A A. Keyboard time limit per test 2 seconds memory limi ...