폴더 기능에 많은 압축 패키지가 포함되어 있으면 압축을 푸는 데 시간이 많이 걸리고 힘들며 특히 중첩된 폴더가 있는 경우 압축을 푸는 것이 더욱 번거롭습니다. 오늘 Frapper는 지정된 경로 아래의 모든 파일과 폴더를 재귀적으로 순회하고 모든 압축된 패키지를 배치로 압축 해제하여 한 번의 클릭으로 압축을 해제하는 방법을 제공합니다.
일반적인 압축 패키지 형식으로는 rar, zip 및 7z가 있습니다.Franpper는 이러한 유형의 파일의 압축 해제 방법을 메서드에 작성합니다.7z를 예로 들어 자세히 소개하겠습니다.전체 코드의 하단을 참조하십시오.
목차
1. 코드 소개
첫 번째는 압축을 푼 파일을 저장할 새 폴더를 만드는 데 사용되는 mkdir 함수 함수입니다.
def mkdir(path):
isExists = os.path.exists(path)
if not isExists:
os.makedirs(path)
print(path + '创建成功')
else:
print(path + '目录已存在')
unzip_log.txt 로그 파일을 생성하여 압축 해제에 실패한 파일의 경로를 기록하고 이러한 파일은 수동으로 압축 해제해야 합니다.
wrong_log = os.path.join(folder_path, 'unzip_log.txt')
폴더를 재귀적으로 탐색할 때 폴더에 있는 모든 폴더의 이름을 가져오십시오. 압축 해제되지 않습니다.
contents = os.listdir(root)
folders = [folder for folder in contents if os.path.isdir(os.path.join(root, folder))]
압축을 풀 파일의 경우 이름을 가져와 폴더를 생성합니다.
zipFile_name = file.split('.')[0:-1]
zipFile_name = '.'.join(zipFile_name)
다음으로 압축 해제 작업을 수행합니다.
with py7zr.SevenZipFile(zipFile_path, mode='r') as z:
z.extractall(path=unzip_zipFile_path)
압축 해제에 실패한 파일의 경로는 로그에 기록됩니다.
with open(wrong_log, 'a') as f:
f.write(f'\n {zipFile_path}')
2. 주의사항
알아야 할 사항은 다음과 같습니다.
1) rarfile을 이용하여 rar 파일의 압축을 해제하면 압축해제에 실패하므로 winrar 디렉토리에 있는 UnRAR.exe를 python 스크립트 디렉토리에 복사해야 합니다. 아래 그림과 같이:
2) zip 파일을 압축할 때 zip 파일을 사용하면 압축을 푼 파일에 글자가 깨져서 나오는데 zipfile.py 파일에서 아래 그림과 같이 두 곳을 수정해야 합니다.
3. 완전한 코드
import os
import zipfile
import rarfile
import py7zr
"""
解压文件
"""
def mkdir(path):
isExists = os.path.exists(path)
if not isExists:
os.makedirs(path)
print(path + '创建成功')
else:
print(path + '目录已存在')
def unzipFile(folder_path):
wrong_log = os.path.join(folder_path, 'unzip_log.txt')
for root, dirs, files in os.walk(folder_path):
contents = os.listdir(root)
folders = [folder for folder in contents if os.path.isdir(os.path.join(root, folder))] # 该目录下文件夹名称列表
for file in files:
if file.endswith('7z'):
zipFile_name = file.split('.')[0:-1]
zipFile_name = '.'.join(zipFile_name)
if zipFile_name in folders:
continue
# 没有重名文件则进行解压
else:
# 创建解压文件夹路径
unzip_zipFile_path = os.path.join(root, zipFile_name)
mkdir(unzip_zipFile_path)
zipFile_path = os.path.join(root, file)
print(zipFile_path)
try:
with py7zr.SevenZipFile(zipFile_path, mode='r') as z:
z.extractall(path=unzip_zipFile_path)
except:
with open(wrong_log, 'a') as f:
f.write(f'\n {zipFile_path}')
elif file.endswith('rar'): # file 是待解压文件
# 有重名文件说明被解压过,跳过
rarFile_name = file.split('.')[0:-1]
rarFile_name = '.'.join(rarFile_name)
if rarFile_name in folders:
continue
# 没有重名文件则进行解压
else:
# 创建解压文件夹路径
unzip_rarFile_path = os.path.join(root, rarFile_name)
mkdir(unzip_rarFile_path)
rarFile_path = os.path.join(root, file)
print(rarFile_path)
try:
with rarfile.RarFile(rarFile_path) as rar_ref:
rar_ref.extractall(unzip_rarFile_path)
except:
pass
with open(wrong_log, 'a') as f:
f.write(f'\n {rarFile_path}')
elif file.endswith('zip'): # file 是待解压文件
# 有重名文件说明被解压过,跳过
rarFile_name = file.split('.')[0:-1]
rarFile_name = '.'.join(rarFile_name)
if rarFile_name in folders:
continue
# 没有重名文件则进行解压
else:
# 创建解压文件夹路径
unzip_rarFile_path = os.path.join(root, rarFile_name)
mkdir(unzip_rarFile_path)
rarFile_path = os.path.join(root, file)
print(rarFile_path)
try:
with zipfile.ZipFile(rarFile_path, 'r') as zip_ref:
zip_ref.extractall(unzip_rarFile_path)
except:
with open(wrong_log, 'a') as f:
f.write(f'\n {rarFile_path}')
else:
continue
unzipFile(r"G:\work\")