本文为博主原创,未经许可严禁转载。
本文链接:https://blog.csdn.net/zyooooxie/article/details/114632112
最近在翻看Python的官方文档,https://docs.python.org/zh-cn/3.7/library/archiving.html ,做些分享;
【本文 实操是 用的 大小不超5M的文件】
个人博客:https://blog.csdn.net/zyooooxie
需求
- 对某文件、某文件list、某文件夹 压缩、解压
- 对某文件、某文件list、某文件夹 使用特定密码 压缩、解压
压缩
https://docs.python.org/zh-cn/3.7/library/zipfile.html
zipfile支持解密 ZIP归档中的加密文件,但是目前不能创建一个加密的文件。我的思路是 用命令行 调用本地EXE来加密压缩;【目前是用的7z;https://www.7-zip.org/】
def exe_zip(command_str: str):
"""
Run command:7z
:param command_str:
:return:
"""
Log.info(command_str)
cp = subprocess.run(args=command_str, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8")
print(cp.stdout)
Log.info(cp.returncode)
assert cp.returncode == 0
def write_one_file(file_path: str, zip_file_name: str, password: str = None):
"""
压缩一个文件
:param file_path:
:param zip_file_name:
:param password:
:return:
"""
Log.info('待压缩文件:{},密码:{}'.format(file_path, password))
if password is None:
with zipfile.ZipFile(zip_file_name, mode='w', compression=zipfile.ZIP_DEFLATED) as zf:
zf.write(file_path, arcname=os.path.basename(file_path))
else:
command_str = ' '.join(['7z', 'a', zip_file_name, '-p{}'.format(password), '{}'.format(file_path)])
exe_zip(command_str)
def write_many_files(file_path: list, zip_file_name: str, password: str = None):
"""
压缩多个文件
:param file_path:
:param zip_file_name:
:param password:
:return:
"""
Log.info('要压缩的文件list:{},密码:{}'.format(file_path, password))
if password is None:
with zipfile.ZipFile(zip_file_name, mode='w', compression=zipfile.ZIP_DEFLATED) as zf:
for f in file_path:
zf.write(f, arcname=os.path.basename(f))
else:
new_file_path = ' '.join(file_path)
print(new_file_path)
command_str = ' '.join(['7z', 'a', zip_file_name, '-p{}'.format(password), '{}'.format(new_file_path)])
exe_zip(command_str)
def write_folder(file_path: str or list, zip_file_name: str, password: str = None, zip_dirs: str = 'yes',
use_7z: str = 'no'):
"""
压缩一个文件夹;
有、无密码,7z都会保持原目录;
无密码时,zipfile可设置 是否保持原目录;
:param file_path:
:param zip_file_name:
:param password:
:param zip_dirs:
:param use_7z:
:return:
"""
Log.info('待压缩的目录:{},密码:{}'.format(file_path, password))
if password is None and use_7z == 'no':
with zipfile.ZipFile(zip_file_name, mode='w', compression=zipfile.ZIP_DEFLATED) as zf:
for root, dirs, files in os.walk(file_path):
f_path = root.replace(file_path, '')
for f in files:
if zip_dirs == 'yes':
zf.write(os.path.join(root, f), arcname=os.path.join(f_path, f))
else:
zf.write(os.path.join(root, f), arcname=f)
else:
file_path += r'\*'
if password is None:
command_str = ' '.join(['7z', 'a', zip_file_name, '{}'.format(file_path)])
else:
command_str = ' '.join(['7z', 'a', zip_file_name, '-p{}'.format(password), '{}'.format(file_path)])
exe_zip(command_str)
def test_write(file_path: str or list, password: str = None, encrypted_file_path: str = None):
"""
压缩文件
:param file_path:
:param password:
:param encrypted_file_path: 不要用中文路径
:return:
"""
zip_file_name = 'zy.zip'
if encrypted_file_path is not None:
zip_file_name = os.path.join(encrypted_file_path, zip_file_name)
if isinstance(file_path, list):
write_many_files(file_path, zip_file_name, password)
elif os.path.isfile(file_path):
write_one_file(file_path, zip_file_name, password)
elif os.path.isdir(file_path):
write_folder(file_path, zip_file_name, password, use_7z='yes')
else:
raise Exception('file_path 不合法')
Log.info('压缩文件:{} 新建成功'.format(zip_file_name))
解压
def test_extractall_zipfile(encrypted_file_path: str, password: str = None, target_dir: str = None):
"""
zipfile解压
:param encrypted_file_path:
:param password:
:param target_dir:
:return:
"""
Log.info('待解压的 zip文件:{},密码:{}'.format(encrypted_file_path, password))
if zipfile.is_zipfile(encrypted_file_path):
with zipfile.ZipFile(encrypted_file_path, 'r') as zf:
Log.info('文件列表:{}'.format(zf.namelist()))
if target_dir is not None:
if password is None:
zf.extractall(path=target_dir)
else:
zf.extractall(pwd=password.encode(), path=target_dir)
else:
if password is None:
zf.extractall()
else:
zf.extractall(pwd=password.encode())
Log.info('解压文件夹:{} 解压成功'.format(target_dir))
def test_extractall_7z(encrypted_file_path: str, password: str = None, target_dir: str = None):
"""
7z解压
:param encrypted_file_path:
:param password:
:param target_dir:
:return:
"""
Log.info('待解压的 zip文件:{},密码:{}'.format(encrypted_file_path, password))
if zipfile.is_zipfile(encrypted_file_path):
if target_dir is None:
target_dir = os.path.abspath(os.getcwd())
if password is not None:
command_str = ' '.join(['7z', 'x', encrypted_file_path, '-p{}'.format(password), '-o{}'.format(target_dir), '-aoa'])
else:
command_str = ' '.join(['7z', 'x', encrypted_file_path, '-o{}'.format(target_dir), '-aoa'])
exe_zip(command_str)
Log.info('解压文件夹:{} 解压成功'.format(target_dir))
本文链接:https://blog.csdn.net/zyooooxie/article/details/114632112
交流技术 欢迎+QQ 153132336 zy
个人博客 https://blog.csdn.net/zyooooxie
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)