让AI生成的一个纠正Assets.xcassets文件夹下,实际的图片名字与在项目中使用的名字不一致的问题,调实际图片名字,更新至contents.json

93 阅读1分钟

#!/usr/local/bin/python3

import os

import json

def update_contents_json_in_directory(directory):

遍历指定目录及其子目录

for root, dirs, files in os.walk(directory):

for file in files:

if file == 'Contents.json':

#AppIcon.appiconset

#获取当前文件夹名字

folder_name = os.path.basename(root)

if folder_name == "AppIcon.appiconset":#AppIcon无需调整

continue

if folder_name.endswith('.imageset'):

folder_name = folder_name[:-len('.imageset')]

print(f"folder_name:{folder_name}")

构建文件的完整路径

contents_json_path = os.path.join(root, file)

读取Contents.json文件

with open(contents_json_path, 'r', encoding='utf-8') as f:

contents = json.load(f)

更新images数组中的filename字段

images = contents.get('images', [])

changed = False

if len(images) == 0:

print(f"非图片描述文件Contents.json,contents_json_path:{contents_json_path},无需调整更新")

continue

for image in images:

print(f"image:{image}")

original_filename = image.get('filename', '')

if original_filename == '':

continue

scale = image['scale']

print(f"original_filename:{original_filename},scale:{scale}")

构造新的文件名

if scale == '2x':

new_filename = f"{folder_name}@2x.png"

elif scale == '3x':

new_filename = f"{folder_name}@3x.png"

if original_filename == new_filename:

continue

changed = True

更新Contents.json中的filename字段

image['filename'] = new_filename

print(f"original_filename:{original_filename},new_filename:{new_filename},image:{image},changed:{changed}")

重命名图片文件

original_file_path = os.path.join(root, original_filename)

new_file_path = os.path.join(root, new_filename)

if os.path.exists(original_file_path):

os.rename(original_file_path, new_file_path)

将更新后的内容与原始内容比较

if changed == True:

写回更新后的Contents.json文件

with open(contents_json_path, 'w', encoding='utf-8') as f:

json.dump(contents, f, ensure_ascii=False, indent=4)

print(f"Updated {contents_json_path}\n")

else:

print(f"No changes detected, {contents_json_path} remains the same.\n")

调用函数,传入目标文件夹路径 'Assets.xcassets'

update_contents_json_in_directory('Assets.xcassets')