Python 文件加密解密函数 - 避免 'file is not a zip file' 错误
import os import docx import openpyxl from tkinter import messagebox
此函数用于实际执行文件加密操作
def encrypt_file(input_file_path, output_file_path, key): try: with open(input_file_path, 'rb') as input_file: with open(output_file_path, 'wb') as output_file: while True: byte = input_file.read(1) if not byte: break encrypted_byte = ord(byte) ^ int(key) output_file.write(bytes([encrypted_byte])) # 根据输出文件的扩展名选择保存方式 file_extension = os.path.splitext(output_file_path)[1] temp_file_path = output_file_path.replace(file_extension, '_temp' + file_extension) os.rename(output_file_path, temp_file_path) if file_extension == '.docx': # 如果是.docx文件,则使用python-docx库保存 doc = docx.Document(temp_file_path) doc.save(output_file_path) elif file_extension == '.xlsx': # 如果是.xlsx文件,则使用openpyxl库保存 wb = openpyxl.load_workbook(temp_file_path) wb.save(output_file_path) os.remove(temp_file_path) return True except Exception as e: messagebox.showerror('Error', str(e)) return False
此函数用于实际执行文件解密操作
def decrypt_file(input_file_path, output_file_path, key): try: with open(input_file_path, 'rb') as input_file: with open(output_file_path, 'wb') as output_file: while True: byte = input_file.read(1) if not byte: break decrypted_byte = ord(byte) ^ int(key) output_file.write(bytes([decrypted_byte])) # 根据输出文件的扩展名选择保存方式 file_extension = os.path.splitext(output_file_path)[1] temp_file_path = output_file_path.replace(file_extension, '_temp' + file_extension) os.rename(output_file_path, temp_file_path) if file_extension == '.docx': # 如果是.docx文件,则使用python-docx库保存 doc = docx.Document(temp_file_path) doc.save(output_file_path) elif file_extension == '.xlsx': # 如果是.xlsx文件,则使用openpyxl库保存 wb = openpyxl.load_workbook(temp_file_path) wb.save(output_file_path) os.remove(temp_file_path) return True except Exception as e: messagebox.showerror('Error', str(e)) return False
原文地址: https://www.cveoy.top/t/topic/oRSX 著作权归作者所有。请勿转载和采集!