python批量加密文件

1.文件名的加密与解密

#coding:utf-8
from docx import Document
import os,sys
from docx.oxml.ns import qn
def file_name(user_dir,style):
    file_list = list()
    for root, dirs, files in os.walk(user_dir):
        for file in files:
            if (os.path.splitext(file)[1] == style):
                file_list.append(os.path.join(root, file))
    return file_list
def lock(path_file):
    #doc = Document(path_file)
    for i in range(len(path_file)):#找到不含地址的文件名
        if(path_file[-i-1]=='\\'):
            name = path_file[-i:]
            path_output = path_file[:-i]
            break
    #print(path_output+name)
    if  name!= sys.argv[0]:  #代码本身文件路径,防止脚本文件放在path路径下时,被一起重命名
        os.rename(os.path.join(path_output,name),os.path.join(path_output,str(list(map(ord,name)))))  #重命名文件
def unlock(path_file):
    for i in range(len(path_file)):#找到不含地址的文件名
        if(path_file[-i-1]=='\\'):
            name = path_file[-i:]
            path_output = path_file[:-i]
            break
    if  name!= sys.argv[0]:  #代码本身文件路径,防止脚本文件放在path路径下时,被一起重命名
        os.rename(os.path.join(path_output,name),os.path.join(path_output,''.join(list(map(chr,eval(name))))))  #重命名文件

def lock_files(path):
    print('输入需要加密的文件后缀:')
    style = input()
    path_files = file_name(path,'.'+style)
    #print(path_files)
    for path_file in path_files:
        lock(path_file) 
def unlock_files(path):
    path_files = file_name(path,'')
    #print(path_files)
    for path_file in path_files:
        unlock(path_file)    
if __name__ == '__main__': 
    global path
    path = '.\\'
    print('菜单:\n1.加密\n2.解密')
    n = eval(input())
    if(n==1):
        lock_files(path)
    else:
        unlock_files(path)

2.docx文件名和文本内容的加密与解密

#coding:utf-8
from docx import Document
import os,sys
from docx.oxml.ns import qn
list_sort = ['\\Ethics\\','\\Famous\\','\\Daily\\']
def file_name(user_dir):
    file_list = list()
    for root, dirs, files in os.walk(user_dir):
        for file in files:
            if (os.path.splitext(file)[1] == '.docx' or os.path.splitext(file)[1] == ''):
                file_list.append(os.path.join(root, file))
    return file_list
def lock(path_file):
    doc = Document(path_file)
    doc_ascii = Document()
    doc_ascii.styles['Normal'].font.name = u'宋体'
    doc_ascii.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
    for i in list_sort:
        if i in path_file:
            sort = i
    for value in doc.paragraphs:  #遍历文档的每一段
        text = value.text
        ascii_str = list(map(ord, text))# 字符串 --> ascii
        if(ascii_str==[]):
            continue
        doc_ascii.add_paragraph(str(ascii_str))
    for i in range(len(path_file)):#找到不含地址的文件名
        if(path_file[-i-1]=='\\'):
            name = path_file[-i:]
            break
    #print(name)
    path_output = path + '加密' + sort
    if not os.path.exists(path_output):
        os.makedirs(path_output)#自动创建文件夹
    doc_ascii.save(path_output + str(list(map(ord,name))) )
def unlock(path_file):
    doc = Document(path_file)
    doc_new = Document()
    doc_new.styles['Normal'].font.name = u'宋体'
    doc_new.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
    for i in list_sort:
        if i in path_file:
            sort = i
    for code in doc.paragraphs:
        code = eval(code.text)
        prot_str = ''.join(map(chr,code))# ascii --> 字符串
        doc_new.add_paragraph(prot_str)
    for i in range(len(path_file)):#找到不含地址的文件名
        if(path_file[-i-1]=='\\'):
            name = path_file[-i:]
            break
    path_output = path + '解密' + sort
    if not os.path.exists(path_output): 
        os.makedirs(path_output)
    doc_new.save(path_output + ''.join(list(map(chr,eval(name)))))

def lock_files(path):
    path_files = file_name(path)
    #print(path_files)
    for path_file in path_files:
        lock(path_file)    
def unlock_files(path):
    path_files = file_name(path)
    #print(path_files)
    for path_file in path_files:
        unlock(path_file)    
if __name__ == '__main__': 
    global path
    path = '.\\'
    lock_files(path)
    #unlock_files(path + '加密\\')

3.在文件名中插入随机数

import os,sys
from random import randint   #导入模块
def add_prefix_files():             #定义函数名称
    old_names = os.listdir(path)  #取路径下的文件名,生成列表
    for old_name in old_names:      #遍历列表下的文件名
        if  old_name!= sys.argv[0]:  #代码本身文件路径,防止脚本文件放在path路径下时,被一起重命名
           if old_name.endswith('.mp4'):   #当文件名以.txt后缀结尾时
                temp = list(old_name)
                for i in range(1,len(temp)):
                    if(temp[i] < 'z' and temp[i]<'a' or temp[i] < 'Z' and temp[i]<'A'):
                        continue
                    else:
                        num = randint(0,9)
                        temp[i] = str(num) + temp[i]
                new_name = ''.join(temp)
                os.rename(os.path.join(path,old_name),os.path.join(path,new_name))  #重命名文件
                #print (old_name,"has been renamed successfully! New name is: ",mark+old_name)  #输出提示

if __name__ == '__main__': 
    path = r'H:\\视频\\娱乐\\娱乐\\PPT\\'   #运行程序前,记得修改主文件夹路径!
    add_prefix_files()         #调用定义的函数,注意名称与定义的函数名一致

4.六种文本加密编码的介绍

from urllib.parse import quote, unquote
import base64,hashlib
string = input()
# 1.utf-8
utf8_code = quote(string,encoding='utf-8') # 默认编码格式是utf-8
prot_str = unquote(utf8_code,encoding='utf-8')
print('utf-8:',utf8_code)
print('解码:',prot_str)
# 2.gbk
gbk_code = quote(string,encoding='gbk')# 设置编码格式
prot_str = unquote(gbk_code,encoding='gbk')# 解码
print('gbk:',gbk_code)
print('解码:',prot_str)    
# 3.base64编码
b64_code = base64.b64encode(string.encode())# 编码:字符串 -> 二进制 -> base64编码
prot_str = base64.b64decode(b64_code).decode()# 解码:base64编码 -> 二进制 -> 字符串
print('base64编码:',b64_code)
print('解码:',prot_str)
# 4.ASCII码
ascii_str = list(map(ord, string))# 字符串 --> ascii
prot_str = ''.join(map(chr, ascii_str))# ascii --> 字符串
print('ASCII码:',ascii_str)
print('解码:',prot_str)
# 5.md5加密(md5加密后不可解密)
md5 = hashlib.md5()# 生成一个MD5对象
md5.update(string.encode('utf-8'))# 使用md5对象里的update方法md5转换
code = md5.hexdigest()# 得到加密后的字符串
print('md5密文:',code)
#6.unicode编码
unicode_str = string.encode("unicode_escape")# 编码
utf8_str = string.encode("utf-8")
gbk_str = string.encode("gbk")
print('unicode:',unicode_str)
print('utf8:',utf8_str)
print('gbk:',gbk_str)
# 解码
print('unicode解码:',unicode_str.decode("unicode_escape"))
print('utf-8解码:',utf8_str.decode()) 
print('gbk解码:',gbk_str.decode("gbk"))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值