有时会遇到需要转换文件格式的情况。例如视频,音频,图片等。
python -m pip install Pillow
)实现音频格式转换
import os
# 要转换的文件所在目录
source_path = "C:\\Users\\cc\\Documents\\work_spaces\\cocos_work\\Tank\\Resources\\music\\"
# 转换后文件的存放目录
des_path = "C:\\Users\\cc\\Documents\\work_spaces\\cocos_work\\Tank\\Resources\\music_revert\\"
# ffmpeg目录
ffmpeg = "C:\\ffmpeg-20200213-6d37ca8-win64-static\\bin\\ffmpeg.exe"
# 得到所有文件
source_file = os.listdir(source_path)
for file_name in source_file:
print(f"正在转换{file_name}...")
# 获得文件名(无后缀)
new_name = file_name[:-4]
# 开始转换
os.system(f"{ffmpeg} -i {source_path}{file_name} {des_path}{new_name}.mp3")
print("转换完毕!")
实现图片格式转换
from PIL import Image
import os
source_path = "C:\\Users\\cc\\Documents\\work_spaces\\cocos_work\\Tank\\Resources\\big\\scorepanel\\"
des_path = "C:\\Users\\cc\\Documents\\work_spaces\\cocos_work\\Tank\\Resources\\images\\score_panel\\"
source_file = os.listdir(source_path)
for file_name in source_file:
print(f"正在转换{source_path}{file_name}")
image = Image.open(f"{source_path}{file_name}")
file_name = file_name[:-4]
print(f"正在保存{des_path}{file_name}.png")
image.save(f"{des_path}{file_name}.png")
print("转换完毕")