import os import shutil import re import sys # Ensure stdout can handle UTF-8 even on Windows if sys.stdout.encoding != 'utf-8': import io sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') base_dir = r"e:\Wiki\2nd" wiki_dir = os.path.join(base_dir, "10_Wiki") def organize(): # Only pick files that start with [[ files = [f for f in os.listdir(base_dir) if f.startswith("[[")] moved_count = 0 for filename in files: file_path = os.path.join(base_dir, filename) try: with open(file_path, "r", encoding="utf-8") as f: content = f.read() # Extract category path match = re.search(r'category:\s*"\[\[(10_Wiki/.*?)\]\]"', content) if match: category_path = match.group(1).replace("/", os.sep) target_dir = os.path.join(base_dir, category_path) if not os.path.exists(target_dir): os.makedirs(target_dir) # New filename: remove [[ and ]], and strip whitespace new_filename = filename.replace("[[", "").replace("]]", "").strip() + ".md" target_path = os.path.join(target_dir, new_filename) print(f"Moving {filename} -> {target_path}") shutil.move(file_path, target_path) moved_count += 1 else: print(f"No category found in {filename}") except Exception as e: print(f"Error processing {filename}: {e}") print(f"Total moved: {moved_count}") if __name__ == "__main__": organize()