先安装好python3和cwebp。
import os
import shutil
g_path_old = '/Users/cz/Downloads/光遇雨宝'
g_folder = '12'
g_exe_path = '/Users/cz/Downloads/libwebp-1.2.1-mac-10.15/bin/cwebp'
g_list_not_png_jpg = []
g_path_new = os.path.abspath('.')
def call_exe(lv_file_input, lv_file_output):
lv_para = "%s %s %s %s"%(g_exe_path, lv_file_input, "-o", lv_file_output)
print(lv_para)
os.system(lv_para)
def png_2_webp(root_path_old, root_path_new):
if os.path.isdir(root_path_new):
shutil.rmtree(root_path_new)
os.mkdir(root_path_new)
for root,dirs,files in os.walk(root_path_old):
for dir in dirs:
lv_dir_full_path_old = os.path.join(root,dir)
lv_dir_full_path_new = lv_dir_full_path_old.replace(g_path_old, g_path_new)
os.mkdir(lv_dir_full_path_new)
for file in files:
if file == '.DS_Store':
continue
lv_full_path_old = os.path.join(root,file)
lv_list = os.path.splitext(file)
lv_ext = lv_list[1]
lv_file_new = lv_list[0] + '.webp'
if lv_ext == '.PNG' or lv_ext == '.png' or lv_ext == '.JPG' or lv_ext == '.jpg' or lv_ext == '.HEIC' or lv_ext == '.heic':
lv_full_path_new = os.path.join(root,lv_file_new)
lv_full_path_new2 = lv_full_path_new.replace(g_path_old, g_path_new)
call_exe(lv_full_path_old, lv_full_path_new2)
elif lv_ext == '.MP4' or lv_ext == '.MOV':
lv_full_path_new = lv_full_path_old.replace(g_path_old, g_path_new)
shutil.copy(lv_full_path_old, lv_full_path_new)
else:
g_list_not_png_jpg.append(lv_full_path_old)
continue
if __name__ == "__main__":
png_2_webp(os.path.join(g_path_old, g_folder), os.path.join(g_path_new, g_folder))