import os
import zipfile
# 将一个文件夹中的所有zip文件重命名
# 重命名规则:使用压缩包中的doc文件的名字来重命名压缩包
path = r"E:\考试结果\temp"
# os.listdir()方法获取文件夹名字,返回数组
file_name_list = os.listdir(path)
for name in file_name_list:
if name.endswith('zip'):
# 创建压缩文件对象,注意在改名前关闭压缩文件,否则 WinError 32
f = zipfile.ZipFile(path + '\\' + name)
for s in f.namelist():
# 因为zipfile文件编码只会使用utf8或cp437,遇到中文文件名会出现乱码,需要编码再解码
try:
new_name = s.encode('cp437').decode('gbk')
except:
new_name = s.encode('cp437').decode('utf-8')
if new_name.endswith(".doc"):
break
f.close()
#
os.rename(path + '\\' + name, path + '\\' + new_name.replace(".doc", ".zip"))
Python 批量修改目录中所有压缩包的文件名
最新推荐文章于 2024-08-06 20:13:04 发布