我们用python来
- 解压
xyz.zip文件到xyz_renamed/文件夹
- 在
renameFile 函数中重命名所需文件(我们只重命名 jpeg 和 png 图像)(我们将名称更改为更低)
- 将重命名的内容再次打包到
xyz_renamed.zip
- 删除
xyz_renamed/文件夹和xyz.zip文件
- 将
xyz_renamed.zip 重命名为xyz.zip
import os
from zipfile import ZipFile
import shutil
# rename the individual file and return the absolute path of the renamed file
def renameFile(root, fileName):
toks = fileName.split('.')
newName = toks[0].lower()+'.'+toks[1]
renamedPath = os.path.join(root,newName)
os.rename(os.path.join(root,fileName),renamedPath)
return renamedPath
def renameFilesInZip(filename):
# Create <filename_without_extension>_renamed folder to extract contents into
head, tail = os.path.split(filename)
newFolder = tail.split('.')[0]
newFolder += '_renamed'
newpath = os.path.join(head, newFolder)
if(not os.path.exists(newpath)):
os.mkdir(newpath)
# extracting contents into newly created folder
print("Extracting files\n")
try:
with ZipFile(filename, 'r', allowZip64=True) as zip_ref:
zip_ref.extractall(newpath)
zip_ref.close()
except ResponseError as err:
print(err)
return -1
# track the files that need to be repackaged in the zip with renamed files
filesToPackage = []
for r, d, f in os.walk(newpath):
for item in f:
# filter the file types that need to be renamed
if item.lower().endswith(('.jpg', '.png')):
# renaming file
renamedPath = renameFile(r, item)
filesToPackage.append(renamedPath)
else:
filesToPackage.append(os.path.join(r,item))
# creating new zip file
print("Writing renamed file\n")
zipObj = ZipFile(os.path.join(head, newFolder)+'.zip', 'w', allowZip64 = True)
for file in filesToPackage:
zipObj.write(file, os.path.relpath(file, newpath))
zipObj.close()
# removing extracted contents and origianl zip file
print('Cleaning up \n')
shutil.rmtree(newpath)
os.remove(filename)
# renaming zipfile with renamed contents to original zipfile name
os.rename(os.path.join(head, newFolder)+'.zip', filename)
使用以下代码调用多个zip文件的重命名函数
if __name__ == '__main__':
# zipfiles with contents to be renamed
zipFiles = ['/usr/app/data/mydata.zip', '/usr/app/data/mydata2.zip']
# do the renaming for all files one by one
for _zip in zipFiles:
renameFilesInZip(_zip)