来自不同平台,不同系统的3000多个zip文件,打算用python的zipfile解压缩,后来发现zip文件对中文处理不友好,尝试了各种办法都是在文件名的编码上出错了。最后没办法用python的调用系统命令完美解决了压缩的文件
def unzip_each_zip_package(path,fn):
try:
if zipfile.is_zipfile(fn):
zf = zipfile.ZipFile(fn)
for fName in zf.namelist():
correct_fn=''
try:
correct_fn = fName.encode('cp437').decode('GBK') #这里就用来编解码的操作的
except:
correct_fn = fName.encode('cp437').decode('utf-8')
if correct_fn.find("__MACOSX")>=0:continue #macos 压缩的文件有__MACOS的隐藏目录,不需要
correct_fn = os.path.join(path, correct_fn)
if not os.path.exists(correct_fn) and str(correct_fn).endswith("/"): #判断文件路径是否存在
os.makedirs(correct_fn) #没有文件路径的创建文件路径
else:
with open(correct_fn , 'wb') as disfile: #创建相应文件
with zf.open(fName, 'r') as srcfile:
shutil.copyfileobj(srcfile, disfile)
else:
print("不是zip文件",fn)
except Exception as error:
print("解压文件出现错误",error)
if zipFile[-3:] == r'zip':
cmd=[r"C:\Program Files\WinRAR\winrar.exe" ,'x','-o+', zipFile,path]
status=subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while True:
if status.poll() == None:
print('程序执行中...')
time.sleep(1)
else:
print('程序执行完毕, 状态码为:%s' % status.poll())
break