You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
2.8 KiB

import os
import sys
import glob
import re
from lxml import etree
def parse_xml(file_path):
"""Parse XML content from a file and return an ElementTree object."""
try:
with open(file_path, "r", encoding="utf-8") as file:
return etree.parse(file)
except etree.XMLSyntaxError:
print(f"Error parsing XML in {file_path}")
return None
def update_target_file(source_tree, target_tree):
"""Update XML properties in the target file only if they exist in the source file,
and add elements from the source file that do not already exist in the target file."""
source_root = source_tree.getroot()
target_root = target_tree.getroot()
source_elements = {elem.tag: elem for elem in source_root}
# Update existing elements in the target file
for target_elem in target_root:
if target_elem.tag in source_elements:
target_elem.text = source_elements[target_elem.tag].text
# Add missing elements from the source file to the target file
for source_elem in source_elements.values():
if not any(target_elem.tag == source_elem.tag for target_elem in target_root):
# If the element is not in target, append it
target_root.append(source_elem)
def process_files(source_dir, target_dir):
"""Process all .nfo files in source_dir and update matching files in target_dir."""
source_files = glob.glob(os.path.join(source_dir, "*.nfo"))
target_dir = re.sub(r'(\[|\])', r'[\1]', target_dir)
target_files = glob.glob(os.path.join(target_dir, "*.nfo"))
for src_file in source_files:
src_filename_base = os.path.splitext(os.path.basename(src_file))[0] # Remove .nfo extension
matching_targets = [tgt for tgt in target_files if src_filename_base in os.path.splitext(os.path.basename(tgt))[0]]
if not matching_targets:
print(f"No matching target file found for: {src_filename_base}")
continue
source_tree = parse_xml(src_file)
if source_tree is None:
continue
for tgt_file in matching_targets:
print(f"Updating file: {tgt_file}")
target_tree = parse_xml(tgt_file)
if target_tree is None:
continue
update_target_file(source_tree, target_tree)
# Save the updated target file
with open(tgt_file, "wb") as f:
target_tree.write(f, encoding="utf-8", xml_declaration=True)
print(f"Updated: {tgt_file}")
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: python script.py <source_directory> <target_directory>")
sys.exit(1)
source_directory = sys.argv[1]
target_directory = sys.argv[2]
process_files(source_directory, target_directory)