Skip to content

Instantly share code, notes, and snippets.

@tewha
Last active July 12, 2025 21:02
Show Gist options
  • Save tewha/9a3ead62d66b236bf10a5d6dc898bdbe to your computer and use it in GitHub Desktop.
Save tewha/9a3ead62d66b236bf10a5d6dc898bdbe to your computer and use it in GitHub Desktop.
Ever been irritated at the internal names of your xcassets images? Use caution, though, this has only been tested with standard (1x), 2x, 3x image sets.
import os
import sys
import json
def rename_asset_images(imageset_path):
if not imageset_path.endswith('.imageset'):
print(f"Skipping {imageset_path}: not an .imageset folder")
return
base_name = os.path.splitext(os.path.basename(imageset_path))[0]
contents_path = os.path.join(imageset_path, 'Contents.json')
if not os.path.exists(contents_path):
print(f"Error: {contents_path} not found.")
return
try:
with open(contents_path, 'r', encoding='utf-8') as f:
contents = json.load(f)
except json.JSONDecodeError as e:
print(f"Error parsing JSON in {contents_path}: {e}")
return
updated = False
for image in contents.get('images', []):
old_filename = image.get('filename')
scale = image.get('scale')
if not old_filename or not scale:
continue
ext = os.path.splitext(old_filename)[1]
new_filename = f"{base_name}@{scale}{ext}" if scale != '1x' else f"{base_name}{ext}"
old_path = os.path.join(imageset_path, old_filename)
new_path = os.path.join(imageset_path, new_filename)
if os.path.exists(old_path) and old_filename != new_filename:
os.rename(old_path, new_path)
image['filename'] = new_filename
print(f"[{base_name}] Renamed: {old_filename} → {new_filename}")
updated = True
elif not os.path.exists(old_path):
print(f"[{base_name}] Warning: {old_filename} not found")
if updated:
with open(contents_path, 'w', encoding='utf-8') as f:
json.dump(contents, f, indent=2)
print(f"[{base_name}] Contents.json updated")
else:
print(f"[{base_name}] No changes made")
# --- CLI usage ---
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Usage: python rename_asset_images.py <*.imageset> [...]")
sys.exit(1)
for path in sys.argv[1:]:
rename_asset_images(path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment