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"))
												
											python批量加密文件的更多相关文章
- python批量进行文件修改操作
		
python批量修改文件扩展名 在网上下载了一些文件,因为某种原因,扩展名多了一个后缀'.xxx',手动修改的话因为文件太多,改起来费时费力,于是决定写个小脚本进行修改. 1.要点: import r ...
 - python 批量创建文件及文件夹(文件夹里再创文件)
		
python 批量创建文件及文件夹(文件夹里再创文件)思路:文件建到哪>文件名字叫啥>创建文件夹>去新建的文件下>新建文件>给文件里边写东西>写个反馈给控制台> ...
 - python批量拷贝文件
		
普通批量拷贝文件 import os import shutil import logging from logging import handlers from colorama import Fo ...
 - python批量json文件转xml文件脚本(附代码)
		
场景:在使用了mask rcnn跑实验后标注了大量地json格式文件,现在打算使用yolo和faster rcnn 跑实验 所以需要将之前地json文件转为xml 但是找了很久,没发现有批量处 ...
 - python批量处理文件夹中文件的问题
		
用os模块读取文件夹中文件 原来的代码: import osfrom scipy.misc import imread filenames=os.listdir(r'./unprocess')for ...
 - python批量修改文件名称
		
参考文章:http://www.cnblogs.com/ma6174/archive/2012/05/04/2482378.html 最近遇到一个问题,在网上下载了一批视频课程,需要将每节课的名称标号 ...
 - python批量删除文件
		
敲代码測试时总会碰到要删除日志目录下的日志或者删除一些历史文件.每次都会生成,再測试的时候为了查找错误原因方便总是要在測试前删除这些文件.手动删除比較麻烦.所以写一个批量删除脚本 import os ...
 - python批量删除文件夹
		
制作的python程序跑一次就占200多内存在temp下面,关键是还不释放,最开始都没有发现这个问题,知道自己的c盘越来越小才发现问题所在.所以就有了去删除temp下生成的文件 代码如下: impor ...
 - python 批量下载文件
		
file.txt 的内容为: http://183.xxx.xxx.54:188/my/qqq.ico::qq.exe::0::http://183.xxx.xxx.54:186/my/ddnf.ic ...
 
随机推荐
- LuoguP1456 Monkey King (左偏树)
			
struct LeftTree{ int l,r,val,dis; }t[N]; int fa[N]; inline int Find(int x){ return x == fa[x] ? x : ...
 - HDU6848改编题(弱化)——客星璀璨之夜(stars)
			
「 客星璀璨之夜 」(stars) " 虽然不清楚是不是那两人的力量 在那个风暴肆虐的夜晚,的确有一瞬 真的在那一瞬间,在云破天开的时候 透过空隙中看到的璀璨星空,不知为何倒映眼中不能忘怀 ...
 - 【java】学习路径42-六种字符流使用实例
			
第一种 OutputStreamWriter OutputStreamReader 第二种 FileWriter FileReader 第三种 BufferedWriter BufferedReade ...
 - QtCreator像C# region一样折叠代码
			
C# #region "comment" [code] #endregion 就可以在VS中实现代码折叠了 QtCreator #pragma region "comme ...
 - KingbaseES V8R6集群维护之--修改数据库服务端口案例
			
 案例说明: 对于KingbaseES数据库单实例环境,只需要修改kingbase.conf文件的'port'参数即可,但是对于KingbaseES V8R6集群中涉及到多个配置文件的修改,并且在应 ...
 - angr原理与实践(二)—— 各类图的生成(CFG CG ACFG DDG等)
			
 本文系原创,转载请说明出处 Please Subscribe Wechat Official Account:信安科研人,获取更多的原创安全资讯 上一篇文章介绍了angr的原理,自此篇文章开始, ...
 - webpack打包优化点
			
目录 1. noParse 2. 包含和排除目录 3. IgnorePlugin 4. happypack 5. DllPlugin动态链接库 6. 热更新 7. 开发环境 tree-shaking ...
 - 来点基础的练习题吧,看见CSDN这类基础的代码不多
			
来点基础的练习题吧,看见CSDN这类基础的代码不多 //正三角形 void ex03(){ int i,k=0, rows, space; printf("请输入三角形的层次:") ...
 - vue项目中使用百度富文本编辑器ueditor
			
第一步,安装依赖,并且把ueditor整个文件夹放入public里边 第二步,在你需要编辑的地方引入,或者main.js中全局引入 XX.vue文件中写入下面代码,创建编辑器. <vue-ued ...
 - 从Kubernetes Event中提取有效信息