# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import os
import re
import codecs
import subprocess
import zipfile
import hashlib
import reportlab
import tkinter as tk
from tkinter import filedialog
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
def get_file_md5(zipfile):
print("选择的文件是:", zipfile)
file = open(f'{zipfile}', 'rb')
content = file.read()
file.close()
print("文件长度:", len(content))
md5_hash = hashlib.md5(content).hexdigest()
return md5_hash
def gbk_to_utf8(gbk_file_path, utf8_file_path):
with codecs.open(gbk_file_path, 'r', 'gbk') as f_gbk:
content = f_gbk.read()
with codecs.open(utf8_file_path, 'w', 'utf-8') as f_utf8:
f_utf8.write(content)
def utf8_to_gbk(gbk_file_path, utf8_file_path):
with codecs.open(utf8_file_path, 'r', 'utf-8') as f_utf8:
content = f_utf8.read()
with codecs.open(gbk_file_path, 'w', 'gbk') as f_gbk:
f_gbk.write(content)
def remove_unuse_file(filename):
try:
os.remove(filename)
print(f"文件 {filename} 已被删除")
except OSError as e:
print(f"删除文件时出错: {filename} : {e.strerror}")
def run_tree_command(path,storefile):
# 注意:这个命令只在CMD环境中有效,所以我们需要指定shell=True
# command = f'tree /f "{path}" > E:\share_dir\ctest\\readme.txt'
command = f'tree /f "{path}" > "{storefile}"'
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
if process.returncode != 0:
print(f"Error occurred: {stderr.decode()}")
else:
print(stdout.decode("UTF-8"))
def rar_compress(source_dir, rar_filename):
# 确保 WinRAR 的 rar.exe 在系统的 PATH 中,或者提供完整的路径
rar_path = 'C:\Program Files\WinRAR\Rar.exe' # 替换为你的 rar.exe 的完整路径,如果它不在 PATH 中
command = [rar_path, 'a', rar_filename, source_dir]
subprocess.run(command, check=True)
def zip_folder(folder_path, zip_filename):
# 创建一个ZipFile对象,'w'表示写入模式,'zipfile.ZIP_DEFLATED'表示使用压缩
with zipfile.ZipFile(zip_filename, 'w', zipfile.ZIP_DEFLATED) as zipf:
# 遍历文件夹中的所有文件和子文件夹
for root, dirs, files in os.walk(folder_path):
# 遍历当前路径下的所有文件
for file in files:
# 构造文件的完整路径
file_path = os.path.join(root, file)
# 使用arcname参数来设置压缩后文件在zip包中的路径
# 使用os.path.relpath来得到相对于folder_path的相对路径
zipf.write(file_path, arcname=os.path.relpath(file_path, folder_path))
def zipdir(path, ziph):
# ziph是zip文件的句柄
for root, dirs, files in os.walk(path):
for file in files:
ziph.write(os.path.join(root, file),
os.path.relpath(os.path.join(root, file),
os.path.join(path, '..')))
def txt_file_record(md5sum, zipfilename,txtfile):
with open(txtfile, 'w', encoding='utf-8') as file:
contex = md5sum+" "+zipfilename
print('write contex:', contex)
file.write(contex)
def pdf_switch(txtfile, pdffile):
# 注册支持中文的字体
pdfmetrics.registerFont(TTFont('SimHei', 'SimHei.ttf')) # 假设你使用的是 'SimHei.ttf' 字体文件
# 创建一个PDF文件
c = canvas.Canvas(pdffile, pagesize=letter)
# 设置字体和字号
c.setFont('SimHei', 11) # 使用刚才注册的字体
# 写入中文文本
with codecs.open(txtfile, 'r', 'utf-8') as file:
content = file.read()
lines = content.split('\r\n')
x_position = 95
y_position=705
for line in lines:
c.drawString(x_position, y_position, line)
y_position -= 15 # 每行下移15个单位
if y_position == 0 :
c.showPage()
y_position = 750
# 注册支持中文的字体
#pdfmetrics.registerFont(TTFont('SimHei', 'SimHei.ttf')) # 假设你使用的是 'SimHei.ttf' 字体文件
# 设置字体和字号
c.setFont('SimHei', 12) # 使用刚才注册的字体
# 保存PDF文件
c.save()
def dir_proc(root_dir):
dirname = os.path.basename(root_dir)
print(f'文件名:{dirname}')
zipfilename = root_dir + '.zip'
readme_file_tmp = root_dir + "\\readme.txt"
run_tree_command(root_dir, readme_file_tmp)
# 使用函数进行转换
readme_file = root_dir + "\\readme_utf8.txt"
gbk_to_utf8(readme_file_tmp, readme_file)
pdffile = root_dir + "\\readme.pdf"
pdf_switch(readme_file, pdffile)
remove_unuse_file(readme_file_tmp)
remove_unuse_file(readme_file)
# zip_folder(root_dir,zipfilename)
zip_filename = root_dir + '.zip' # 压缩后的zip文件名
with zipfile.ZipFile(zip_filename, 'w', zipfile.ZIP_DEFLATED) as zipf:
zipdir(root_dir, zipf)
print(f'输出压缩文件:“{zipfilename}”')
md5sum = get_file_md5(zipfilename)
print(f'md5:{md5sum}')
tmputf8_txt = root_dir + '_utf8.txt'
txt_file_record(md5sum, dirname + '.zip', tmputf8_txt)
utf8_to_gbk(root_dir + '.txt', tmputf8_txt)
remove_unuse_file(tmputf8_txt)
def select_directory_proc():
directory = filedialog.askdirectory()
if directory:
# 清除之前的路径(如果有的话)
directory_label.config(text="")
# 在标签中显示所选目录的路径
display_txt = directory+"\n"
display_txt += directory + ".txt"+"\n"
display_txt += directory + ".zip" + "\n"
directory_label.config(text=display_txt)
dir_proc(directory)
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
root = tk.Tk()
root.geometry('512x256')
root.title('文件夹打包压缩工具')
# 创建一个标签用于显示所选目录的路径
directory_label = tk.Label(root, text="")
directory_label.pack(pady=20)
# 创建一个按钮,点击时调用select_directory函数
select_button = tk.Button(root, text="选择目录", command=select_directory_proc)
select_button.pack(pady=10)
root.mainloop()