读取JSON信息并重命名文件:Python代码静默失败原因排查
代码静默失败原因分析与修复
需求说明
- 读取指定文件夹及其子文件夹中的
.json文件 - 提取文件中名为
MediaList的数组(示例结构如下)
"MediaList": [ { "ObjectName": "AkMediaAsset'89357021'", "ObjectPath": "/Game/WwiseAudio/Media/89357021.0" }, { "ObjectName": "AkMediaAsset'152710780'", "ObjectPath": "/Game/WwiseAudio/Media/152710780.0" } ]
- 根据
MediaList中ObjectName字段的编号,找到目标路径下对应的文件 - 将找到的文件重命名为对应JSON文件名加序号(如
_1、_2)的形式
用户问题
作为编程新手,编写的Python代码出现静默失败(无任何输出、未执行预期操作),代码如下:
import os import json # Define the folder path where the JSON files are located json_folder = r'C:\Resources\Tools\FModel\FModel\Output\Exports\remnant2\Game\WwiseAudio\Events' # Define the folder path where the WEM files are located wem_folder = r'C:\Resources\Tools\FModel\FModel\Output\Exports\remnant2\Game\WwiseAudio\Media' # Iterate through the JSON files for root, dirs, files in os.walk(json_folder): for file in files: if file.endswith('.json'): json_file_path = os.path.join(root, file) # Read the JSON file with open(json_file_path, 'r') as json_file: data = json.load(json_file) # Check if "MediaList" exists in JSON data if "MediaList" in data: media_list = data["MediaList"] # Iterate through the media list for index, media_item in enumerate(media_list): object_name = media_item.get("ObjectName", '') if object_name: # Extract the number from the ObjectName number = object_name.split("'")[1] # Construct the new WEM file name new_wem_name = f'{file.split(".")[0]}_{number}.wem' # Rename the WEM file wem_path = os.path.join(wem_folder, f'{number}.wem') new_wem_path = os.path.join(wem_folder, new_wem_name) try: os.rename(wem_path, new_wem_path) print(f'Renamed {wem_path} to {new_wem_name}') except FileNotFoundError: print(f'File {wem_path} not found, skipping.')
静默失败的核心原因
- 缺失关键异常捕获:JSON解析失败、文件读取权限不足、
ObjectName格式不符合预期时,程序会直接崩溃但无任何提示,看起来像"静默失败"。 - 路径配置错误:如果
json_folder或wem_folder路径填写错误,程序遍历不到目标文件,自然不会执行任何操作。 MediaList字段缺失:若所有JSON文件都没有MediaList字段,代码会跳过所有后续逻辑,无输出。- 需求理解偏差:原代码用
ObjectName中的编号作为后缀,而非需求要求的序号(_1、_2),即使执行也不符合预期。
修复后的代码
import os import json # 配置目标路径 json_folder = r'C:\Resources\Tools\FModel\FModel\Output\Exports\remnant2\Game\WwiseAudio\Events' wem_folder = r'C:\Resources\Tools\FModel\FModel\Output\Exports\remnant2\Game\WwiseAudio\Media' # 遍历所有JSON文件 for root, dirs, files in os.walk(json_folder): print(f"正在遍历目录: {root}") for file in files: if not file.endswith('.json'): continue json_file_path = os.path.join(root, file) print(f"处理文件: {json_file_path}") # 处理文件读取与JSON解析异常 try: with open(json_file_path, 'r', encoding='utf-8') as json_file: try: data = json.load(json_file) except json.JSONDecodeError as e: print(f"JSON解析失败: {str(e)},跳过该文件") continue except PermissionError: print(f"无权限读取该文件,跳过") continue # 检查MediaList字段 if "MediaList" not in data: print(f"文件中未找到MediaList字段,跳过") continue media_list = data["MediaList"] print(f"找到{len(media_list)}个媒体项") for index, media_item in enumerate(media_list, start=1): object_name = media_item.get("ObjectName", '') if not object_name: print(f"第{index}个媒体项缺失ObjectName,跳过") continue # 提取编号并处理格式异常 try: number = object_name.split("'")[1] except IndexError: print(f"ObjectName格式错误: {object_name},无法提取编号,跳过") continue # 按需求构造新文件名(使用序号作为后缀) new_wem_name = f'{file.split(".")[0]}_{index}.wem' wem_path = os.path.join(wem_folder, f'{number}.wem') new_wem_path = os.path.join(wem_folder, new_wem_name) # 执行重命名并处理异常 try: if os.path.exists(wem_path): os.rename(wem_path, new_wem_path) print(f"重命名成功: {wem_path} -> {new_wem_name}") else: print(f"目标文件不存在: {wem_path},跳过") except PermissionError: print(f"无权限重命名文件,跳过") except Exception as e: print(f"重命名失败: {str(e)},跳过")
修复要点
- 增加了全流程日志输出,方便定位问题
- 捕获了文件读取、JSON解析、格式错误、权限等所有可能的异常,避免静默崩溃
- 修正了文件名后缀逻辑,使用遍历序号替代原编号,符合需求
- 增加了文件存在性检查,减少无效操作
内容的提问来源于stack exchange,提问作者Angry Crow Man
相关产品推荐
相关产品推荐

