编写Python脚本批量修改JSON文件中tagid的前缀
Hey there! Let's get that Python script fixed up to batch update those JSON files correctly. I'll share the corrected code first, then break down the common pitfalls that might have messed up your initial attempt.
Corrected Python Script
import os import json def batch_update_tagid_prefix(target_dir): # Walk through all files in the target directory (including subfolders, remove os.walk if not needed) for root, _, files in os.walk(target_dir): for filename in files: if not filename.endswith('.json'): continue file_path = os.path.join(root, filename) try: # Read the JSON file with proper encoding with open(file_path, 'r', encoding='utf-8') as f: data = json.load(f) # Validate the structure has the required array if 'rpt_animrec' not in data or not isinstance(data['rpt_animrec'], list): print(f"Skipping {filename}: Missing or invalid 'rpt_animrec' array") continue updated = False # Iterate over each object in the rpt_animrec array for anim_item in data['rpt_animrec']: # Safely access nested fields to avoid KeyErrors if 'grp_animrec' not in anim_item: continue grp_data = anim_item['grp_animrec'] tagid = grp_data.get('tagid') # Only update if tagid exists and starts with TZN if tagid and tagid.startswith('TZN'): # Replace ONLY the first occurrence of TZN (avoids replacing it later in the string) grp_data['tagid'] = tagid.replace('TZN', 'ETH', 1) updated = True # Write changes back to file ONLY if updates were made if updated: # Create a backup first to avoid data loss backup_path = f"{file_path}.bak" os.rename(file_path, backup_path) # Write with indentation and preserve non-ASCII characters with open(file_path, 'w', encoding='utf-8') as f: json.dump(data, f, indent=4, ensure_ascii=False) print(f"Successfully updated {filename} | Backup saved to {backup_path}") else: print(f"No updates needed for {filename}") except json.JSONDecodeError: print(f"Error processing {filename}: Not a valid JSON file") except PermissionError: print(f"Error processing {filename}: Permission denied") except Exception as e: print(f"Unexpected error with {filename}: {str(e)}") if __name__ == "__main__": # Replace this with your target directory path TARGET_DIRECTORY = "./your_json_files_folder" batch_update_tagid_prefix(TARGET_DIRECTORY)
Key Fixes & Explanations
Here are the most common issues that probably broke your initial code, and how this version addresses them:
- Safe nested field access: Instead of directly accessing
anim_item['grp_animrec']['tagid'](which throws a KeyError if any field is missing), we useget()and explicit checks for each nested level. This prevents the script from crashing halfway through. - Directory traversal: Uses
os.walk()to hit all JSON files in the target directory AND its subfolders (removeos.walkand useos.listdirif you don't need subfolders). - Selective replacement: Uses
replace('TZN', 'ETH', 1)to only replace the first occurrence of the prefix, so if "TZN" appears later in the tagid string, it won't get changed accidentally. - Data safety: Creates a backup of each modified file (with
.bakextension) before writing changes, so you can revert if something goes wrong. - Error handling: Catches common issues like invalid JSON, permission errors, and unexpected exceptions, so the script keeps running instead of crashing on one bad file.
- Proper JSON writing: Uses
indent=4to keep the output formatted nicely, andensure_ascii=Falseto preserve any non-ASCII characters in your JSON.
Quick Usage Tips
- Replace
./your_json_files_folderwith the actual path to your directory of JSON files. - Test with a small set of files first to make sure it works as expected.
- If you don't need to process subfolders, swap out the
os.walkloop with a simpleos.listdirloop:for filename in os.listdir(target_dir): file_path = os.path.join(target_dir, filename) if not os.path.isfile(file_path) or not filename.endswith('.json'): continue # rest of the code stays the same
内容的提问来源于stack exchange,提问作者Mirieri Mogaka
相关产品推荐
相关产品推荐

