[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6H9RY5DGDNRYTQRGSH5VXC5":3,"skill-same:01M6H9RY5DGDNRYTQRGSH5VXC5":54},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":24,"linkOnly":25,"markdownContent":26,"markdownBody":27,"frontMatter":28,"refName":32,"commitSha":33,"skillDirectory":34,"forksCount":14,"repositoryHtmlUrl":35,"repositoryHomepageUrl":6,"ownerHtmlUrl":36,"ownerBlogUrl":37,"ownerDescription":38,"updatedAt":39,"install":40,"resources":53},"01M6H9RY5DGDNRYTQRGSH5VXC5","file-handling",null,"File handling and I\u002FO best practices","NeuralBlitz\u002FMito","NeuralBlitz","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F79354388?v=4","01M6H8T2TFH477HRS0KTSTKR2E","David Riggs","01M6H8T2YQQDXPYM092P670Z21",0,"MIT","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Ffile-handling\u002FSKILL.md",[],[19,20,21,22,23],"file","file handling","best practices","opencode","Utilities","2026-11-10 10:12:30",false,"---\nname: file-handling\ndescription: File handling and I\u002FO best practices\nlicense: MIT\ncompatibility: opencode\nmetadata:\n  audience: developers\n  category: utilities\n---\n## What I do\n- Handle file operations safely\n- Process large files efficiently\n- Handle file uploads and downloads\n- Manage file permissions\n- Process different file formats\n- Handle encoding issues\n- Implement streaming for large files\n- Secure file operations\n\n## When to use me\nWhen implementing file handling, uploads, or processing.\n\n## Safe File Operations\n```python\nimport os\nimport tempfile\nimport shutil\nfrom pathlib import Path\nfrom typing import Optional, BinaryIO\nimport hashlib\n\n\nclass SafeFileHandler:\n    \"\"\"Safe file operations with validation.\"\"\"\n    \n    ALLOWED_EXTENSIONS = {'.txt', '.csv', '.json', '.png', '.jpg', '.pdf'}\n    MAX_FILE_SIZE = 10 * 1024 * 1024  # 10MB\n    BLOCK_SIZE = 8192\n    \n    @staticmethod\n    def validate_file_path(base_dir: Path, filename: str) -> Path:\n        \"\"\"\n        Validate and sanitize file path.\n        Prevents path traversal attacks.\n        \"\"\"\n        filename = Path(filename).name  # Remove directories\n        \n        safe_path = (base_dir \u002F filename).resolve()\n        \n        # Ensure path is within base directory\n        if not str(safe_path).startswith(str(base_dir.resolve())):\n            raise SecurityError(\"Invalid file path\")\n        \n        return safe_path\n    \n    @staticmethod\n    def validate_extension(filename: str) -> str:\n        \"\"\"Validate file extension.\"\"\"\n        ext = Path(filename).suffix.lower()\n        \n        if ext not in SafeFileHandler.ALLOWED_EXTENSIONS:\n            raise ValidationError(\n                f\"File type not allowed. \"\n                f\"Allowed: {SafeFileHandler.ALLOWED_EXTENSIONS}\"\n            )\n        \n        return ext\n    \n    @staticmethod\n    def validate_size(size: int) -> None:\n        \"\"\"Validate file size.\"\"\"\n        if size > SafeFileHandler.MAX_FILE_SIZE:\n            raise ValidationError(\n                f\"File too large. Max size: {SafeFileHandler.MAX_FILE_SIZE} bytes\"\n            )\n    \n    @staticmethod\n    def calculate_checksum(file_path: Path) -> str:\n        \"\"\"Calculate MD5 checksum of file.\"\"\"\n        hash_md5 = hashlib.md5()\n        \n        with open(file_path, \"rb\") as f:\n            for chunk in iter(lambda: f.read(SafeFileHandler.BLOCK_SIZE), b\"\"):\n                hash_md5.update(chunk)\n        \n        return hash_md5.hexdigest()\n```\n\n## File Upload Handling\n```python\nimport aiofiles\nfrom fastapi import UploadFile, HTTPException\nfrom starlette.datastructures import UploadFile as StarletteUploadFile\nimport tempfile\nimport os\n\n\nclass FileUploader:\n    \"\"\"Handle file uploads securely.\"\"\"\n    \n    UPLOAD_DIR = Path(\"\u002Fuploads\")\n    MAX_FILE_SIZE = 50 * 1024 * 1024  # 50MB\n    \n    def __init__(self, upload_dir: Path = None) -> None:\n        self.upload_dir = upload_dir or self.UPLOAD_DIR\n        self.upload_dir.mkdir(parents=True, exist_ok=True)\n    \n    async def save_upload(\n        self,\n        file: UploadFile,\n        user_id: str,\n        max_size: int = None\n    ) -> str:\n        \"\"\"\n        Save uploaded file to disk.\n        \n        Returns:\n            File path relative to upload directory\n        \"\"\"\n        max_size = max_size or self.MAX_FILE_SIZE\n        \n        # Validate size\n        file_size = 0\n        content = b\"\"\n        \n        async for chunk in file:\n            file_size += len(chunk)\n            if file_size > max_size:\n                raise HTTPException(\n                    status_code=413,\n                    detail=\"File too large\"\n                )\n            content += chunk\n        \n        # Generate safe filename\n        file_ext = self._get_extension(file.filename)\n        safe_filename = self._generate_safe_filename(user_id, file_ext)\n        file_path = self.upload_dir \u002F safe_filename\n        \n        # Write to disk\n        async with aiofiles.open(file_path, 'wb') as f:\n            await f.write(content)\n        \n        return str(file_path.relative_to(self.upload_dir))\n    \n    def _get_extension(self, filename: Optional[str]) -> str:\n        \"\"\"Get file extension.\"\"\"\n        if not filename:\n            return \"\"\n        return Path(filename).suffix.lower()\n    \n    def _generate_safe_filename(self, user_id: str, ext: str) -> str:\n        \"\"\"Generate unique, safe filename.\"\"\"\n        import uuid\n        timestamp = datetime.utcnow().strftime(\"%Y%m%d\")\n        unique_id = str(uuid.uuid4())[:8]\n        return f\"{user_id}_{timestamp}_{unique_id}{ext}\"\n    \n    async def delete_file(self, file_path: str) -> None:\n        \"\"\"Delete uploaded file.\"\"\"\n        full_path = self.upload_dir \u002F file_path\n        \n        if full_path.exists():\n            full_path.unlink()\n    \n    async def cleanup_user_uploads(self, user_id: str) -> None:\n        \"\"\"Clean up all uploads for a user.\"\"\"\n        import glob\n        \n        pattern = str(self.upload_dir \u002F f\"{user_id}_*\")\n        for file_path in glob.glob(pattern):\n            os.remove(file_path)\n```\n\n## Streaming Large Files\n```python\nimport asyncio\nfrom typing import AsyncIterator\n\n\nclass FileStreamer:\n    \"\"\"Stream large files efficiently.\"\"\"\n    \n    CHUNK_SIZE = 64 * 1024  # 64KB chunks\n    \n    @staticmethod\n    async def stream_file(\n        file_path: Path,\n        chunk_size: int = None\n    ) -> AsyncIterator[bytes]:\n        \"\"\"\n        Stream file in chunks.\n        Memory efficient for large files.\n        \"\"\"\n        chunk_size = chunk_size or FileStreamer.CHUNK_SIZE\n        \n        with open(file_path, 'rb') as f:\n            while True:\n                chunk = f.read(chunk_size)\n                if not chunk:\n                    break\n                yield chunk\n    \n    @staticmethod\n    async def stream_to_response(\n        file_path: Path,\n        response,\n        content_type: str = \"application\u002Foctet-stream\"\n    ) -> None:\n        \"\"\"Stream file to HTTP response.\"\"\"\n        response.headers[\"Content-Disposition\"] = (\n            f\"attachment; filename={file_path.name}\"\n        )\n        response.headers[\"Content-Type\"] = content_type\n        \n        async for chunk in FileStreamer.stream_file(file_path):\n            await response.write(chunk)\n    \n    @staticmethod\n    async def process_large_csv(\n        input_path: Path,\n        output_path: Path,\n        processor: callable\n    ) -> None:\n        \"\"\"\n        Process large CSV without loading into memory.\n        \"\"\"\n        import csv\n        \n        with open(input_path, 'r', newline='', encoding='utf-8') as infile, \\\n             open(output_path, 'w', newline='', encoding='utf-8') as outfile:\n            \n            reader = csv.DictReader(infile)\n            writer = csv.DictWriter(outfile, fieldnames=reader.fieldnames)\n            \n            writer.writeheader()\n            \n            for row in reader:\n                processed_row = processor(row)\n                if processed_row:\n                    writer.writerow(processed_row)\n```\n\n## File Format Processing\n```python\nimport json\nimport csv\nimport xml.etree.ElementTree as ET\nfrom abc import ABC, abstractmethod\nfrom pathlib import Path\nfrom typing import List, Dict, Any\n\n\nclass FileParser(ABC):\n    \"\"\"Base class for file parsers.\"\"\"\n    \n    @abstractmethod\n    def parse(self, file_path: Path) -> List[Dict[str, Any]]:\n        \"\"\"Parse file and return data.\"\"\"\n        pass\n    \n    @abstractmethod\n    def serialize(self, data: List[Dict[str, Any]], file_path: Path) -> None:\n        \"\"\"Serialize data to file.\"\"\"\n        pass\n\n\nclass JSONParser(FileParser):\n    \"\"\"Parse JSON files.\"\"\"\n    \n    def parse(self, file_path: Path) -> List[Dict[str, Any]]:\n        with open(file_path, 'r', encoding='utf-8') as f:\n            data = json.load(f)\n            return data if isinstance(data, list) else [data]\n    \n    def serialize(\n        self,\n        data: List[Dict[str, Any]],\n        file_path: Path\n    ) -> None:\n        with open(file_path, 'w', encoding='utf-8') as f:\n            json.dump(data, f, indent=2, ensure_ascii=False)\n\n\nclass CSVParser(FileParser):\n    \"\"\"Parse CSV files.\"\"\"\n    \n    def __init__(self, delimiter: str = ',') -> None:\n        self.delimiter = delimiter\n    \n    def parse(self, file_path: Path) -> List[Dict[str, Any]]:\n        with open(file_path, 'r', encoding='utf-8') as f:\n            reader = csv.DictReader(f, delimiter=self.delimiter)\n            return list(reader)\n    \n    def serialize(\n        self,\n        data: List[Dict[str, Any]],\n        file_path: Path\n    ) -> None:\n        if not data:\n            return\n        \n        with open(file_path, 'w', encoding='utf-8', newline='') as f:\n            fieldnames = data[0].keys()\n            writer = csv.DictWriter(\n                f,\n                fieldnames=fieldnames,\n                delimiter=self.delimiter\n            )\n            writer.writeheader()\n            writer.writerows(data)\n\n\nclass XMLParser(FileParser):\n    \"\"\"Parse XML files.\"\"\"\n    \n    def __init__(self, root_element: str, record_element: str) -> None:\n        self.root_element = root_element\n        self.record_element = record_element\n    \n    def parse(self, file_path: Path) -> List[Dict[str, Any]]:\n        tree = ET.parse(file_path)\n        root = tree.getroot()\n        \n        results = []\n        for record in root.findall(self.record_element):\n            results.append(self._element_to_dict(record))\n        \n        return results\n    \n    def _element_to_dict(self, element: ET.Element) -> Dict[str, Any]:\n        \"\"\"Convert XML element to dictionary.\"\"\"\n        result = {}\n        \n        for child in element:\n            result[child.tag] = child.text or \"\"\n        \n        return result\n    \n    def serialize(\n        self,\n        data: List[Dict[str, Any]],\n        file_path: Path\n    ) -> None:\n        root = ET.Element(self.root_element)\n        \n        for record in data:\n            record_elem = ET.SubElement(root, self.record_element)\n            for key, value in record.items():\n                child = ET.SubElement(record_elem, key)\n                child.text = str(value)\n        \n        tree = ET.ElementTree(root)\n        tree.write(file_path, encoding='utf-8', xml_declaration=True)\n\n\n# Factory for parsers\nclass ParserFactory:\n    \"\"\"Factory for creating file parsers.\"\"\"\n    \n    PARSERS = {\n        '.json': JSONParser,\n        '.csv': CSVParser,\n        '.xml': XMLParser,\n    }\n    \n    @classmethod\n    def get_parser(cls, file_path: Path) -> FileParser:\n        \"\"\"Get appropriate parser for file extension.\"\"\"\n        ext = file_path.suffix.lower()\n        \n        parser_class = cls.PARSERS.get(ext)\n        if not parser_class:\n            raise ValueError(f\"No parser for extension: {ext}\")\n        \n        return parser_class()\n    \n    @classmethod\n    def parse_file(cls, file_path: Path) -> List[Dict[str, Any]]:\n        \"\"\"Parse file using appropriate parser.\"\"\"\n        parser = cls.get_parser(file_path)\n        return parser.parse(file_path)\n```\n\n## Best Practices\n```\n1. Use context managers\n   with open() as f:\n       # File automatically closed\n\n2. Handle encoding explicitly\n   open(path, 'r', encoding='utf-8')\n\n3. Use streaming for large files\n   Don't load into memory\n\n4. Validate file types\n   Check magic numbers, not just extensions\n\n5. Use secure paths\n   Prevent path traversal\n\n6. Set proper permissions\n   chmod 644 for files, 755 for scripts\n\n7. Handle I\u002FO errors\n   Try-except around file operations\n\n8. Use temporary files\n   For processing sensitive data\n\n9. Clean up resources\n   Delete temp files, close handles\n\n10. Use async I\u002FO\n    For high-concurrency servers\n```\n","## What I do\n- Handle file operations safely\n- Process large files efficiently\n- Handle file uploads and downloads\n- Manage file permissions\n- Process different file formats\n- Handle encoding issues\n- Implement streaming for large files\n- Secure file operations\n\n## When to use me\nWhen implementing file handling, uploads, or processing.\n\n## Safe File Operations\n```python\nimport os\nimport tempfile\nimport shutil\nfrom pathlib import Path\nfrom typing import Optional, BinaryIO\nimport hashlib\n\n\nclass SafeFileHandler:\n    \"\"\"Safe file operations with validation.\"\"\"\n    \n    ALLOWED_EXTENSIONS = {'.txt', '.csv', '.json', '.png', '.jpg', '.pdf'}\n    MAX_FILE_SIZE = 10 * 1024 * 1024  # 10MB\n    BLOCK_SIZE = 8192\n    \n    @staticmethod\n    def validate_file_path(base_dir: Path, filename: str) -> Path:\n        \"\"\"\n        Validate and sanitize file path.\n        Prevents path traversal attacks.\n        \"\"\"\n        filename = Path(filename).name  # Remove directories\n        \n        safe_path = (base_dir \u002F filename).resolve()\n        \n        # Ensure path is within base directory\n        if not str(safe_path).startswith(str(base_dir.resolve())):\n            raise SecurityError(\"Invalid file path\")\n        \n        return safe_path\n    \n    @staticmethod\n    def validate_extension(filename: str) -> str:\n        \"\"\"Validate file extension.\"\"\"\n        ext = Path(filename).suffix.lower()\n        \n        if ext not in SafeFileHandler.ALLOWED_EXTENSIONS:\n            raise ValidationError(\n                f\"File type not allowed. \"\n                f\"Allowed: {SafeFileHandler.ALLOWED_EXTENSIONS}\"\n            )\n        \n        return ext\n    \n    @staticmethod\n    def validate_size(size: int) -> None:\n        \"\"\"Validate file size.\"\"\"\n        if size > SafeFileHandler.MAX_FILE_SIZE:\n            raise ValidationError(\n                f\"File too large. Max size: {SafeFileHandler.MAX_FILE_SIZE} bytes\"\n            )\n    \n    @staticmethod\n    def calculate_checksum(file_path: Path) -> str:\n        \"\"\"Calculate MD5 checksum of file.\"\"\"\n        hash_md5 = hashlib.md5()\n        \n        with open(file_path, \"rb\") as f:\n            for chunk in iter(lambda: f.read(SafeFileHandler.BLOCK_SIZE), b\"\"):\n                hash_md5.update(chunk)\n        \n        return hash_md5.hexdigest()\n```\n\n## File Upload Handling\n```python\nimport aiofiles\nfrom fastapi import UploadFile, HTTPException\nfrom starlette.datastructures import UploadFile as StarletteUploadFile\nimport tempfile\nimport os\n\n\nclass FileUploader:\n    \"\"\"Handle file uploads securely.\"\"\"\n    \n    UPLOAD_DIR = Path(\"\u002Fuploads\")\n    MAX_FILE_SIZE = 50 * 1024 * 1024  # 50MB\n    \n    def __init__(self, upload_dir: Path = None) -> None:\n        self.upload_dir = upload_dir or self.UPLOAD_DIR\n        self.upload_dir.mkdir(parents=True, exist_ok=True)\n    \n    async def save_upload(\n        self,\n        file: UploadFile,\n        user_id: str,\n        max_size: int = None\n    ) -> str:\n        \"\"\"\n        Save uploaded file to disk.\n        \n        Returns:\n            File path relative to upload directory\n        \"\"\"\n        max_size = max_size or self.MAX_FILE_SIZE\n        \n        # Validate size\n        file_size = 0\n        content = b\"\"\n        \n        async for chunk in file:\n            file_size += len(chunk)\n            if file_size > max_size:\n                raise HTTPException(\n                    status_code=413,\n                    detail=\"File too large\"\n                )\n            content += chunk\n        \n        # Generate safe filename\n        file_ext = self._get_extension(file.filename)\n        safe_filename = self._generate_safe_filename(user_id, file_ext)\n        file_path = self.upload_dir \u002F safe_filename\n        \n        # Write to disk\n        async with aiofiles.open(file_path, 'wb') as f:\n            await f.write(content)\n        \n        return str(file_path.relative_to(self.upload_dir))\n    \n    def _get_extension(self, filename: Optional[str]) -> str:\n        \"\"\"Get file extension.\"\"\"\n        if not filename:\n            return \"\"\n        return Path(filename).suffix.lower()\n    \n    def _generate_safe_filename(self, user_id: str, ext: str) -> str:\n        \"\"\"Generate unique, safe filename.\"\"\"\n        import uuid\n        timestamp = datetime.utcnow().strftime(\"%Y%m%d\")\n        unique_id = str(uuid.uuid4())[:8]\n        return f\"{user_id}_{timestamp}_{unique_id}{ext}\"\n    \n    async def delete_file(self, file_path: str) -> None:\n        \"\"\"Delete uploaded file.\"\"\"\n        full_path = self.upload_dir \u002F file_path\n        \n        if full_path.exists():\n            full_path.unlink()\n    \n    async def cleanup_user_uploads(self, user_id: str) -> None:\n        \"\"\"Clean up all uploads for a user.\"\"\"\n        import glob\n        \n        pattern = str(self.upload_dir \u002F f\"{user_id}_*\")\n        for file_path in glob.glob(pattern):\n            os.remove(file_path)\n```\n\n## Streaming Large Files\n```python\nimport asyncio\nfrom typing import AsyncIterator\n\n\nclass FileStreamer:\n    \"\"\"Stream large files efficiently.\"\"\"\n    \n    CHUNK_SIZE = 64 * 1024  # 64KB chunks\n    \n    @staticmethod\n    async def stream_file(\n        file_path: Path,\n        chunk_size: int = None\n    ) -> AsyncIterator[bytes]:\n        \"\"\"\n        Stream file in chunks.\n        Memory efficient for large files.\n        \"\"\"\n        chunk_size = chunk_size or FileStreamer.CHUNK_SIZE\n        \n        with open(file_path, 'rb') as f:\n            while True:\n                chunk = f.read(chunk_size)\n                if not chunk:\n                    break\n                yield chunk\n    \n    @staticmethod\n    async def stream_to_response(\n        file_path: Path,\n        response,\n        content_type: str = \"application\u002Foctet-stream\"\n    ) -> None:\n        \"\"\"Stream file to HTTP response.\"\"\"\n        response.headers[\"Content-Disposition\"] = (\n            f\"attachment; filename={file_path.name}\"\n        )\n        response.headers[\"Content-Type\"] = content_type\n        \n        async for chunk in FileStreamer.stream_file(file_path):\n            await response.write(chunk)\n    \n    @staticmethod\n    async def process_large_csv(\n        input_path: Path,\n        output_path: Path,\n        processor: callable\n    ) -> None:\n        \"\"\"\n        Process large CSV without loading into memory.\n        \"\"\"\n        import csv\n        \n        with open(input_path, 'r', newline='', encoding='utf-8') as infile, \\\n             open(output_path, 'w', newline='', encoding='utf-8') as outfile:\n            \n            reader = csv.DictReader(infile)\n            writer = csv.DictWriter(outfile, fieldnames=reader.fieldnames)\n            \n            writer.writeheader()\n            \n            for row in reader:\n                processed_row = processor(row)\n                if processed_row:\n                    writer.writerow(processed_row)\n```\n\n## File Format Processing\n```python\nimport json\nimport csv\nimport xml.etree.ElementTree as ET\nfrom abc import ABC, abstractmethod\nfrom pathlib import Path\nfrom typing import List, Dict, Any\n\n\nclass FileParser(ABC):\n    \"\"\"Base class for file parsers.\"\"\"\n    \n    @abstractmethod\n    def parse(self, file_path: Path) -> List[Dict[str, Any]]:\n        \"\"\"Parse file and return data.\"\"\"\n        pass\n    \n    @abstractmethod\n    def serialize(self, data: List[Dict[str, Any]], file_path: Path) -> None:\n        \"\"\"Serialize data to file.\"\"\"\n        pass\n\n\nclass JSONParser(FileParser):\n    \"\"\"Parse JSON files.\"\"\"\n    \n    def parse(self, file_path: Path) -> List[Dict[str, Any]]:\n        with open(file_path, 'r', encoding='utf-8') as f:\n            data = json.load(f)\n            return data if isinstance(data, list) else [data]\n    \n    def serialize(\n        self,\n        data: List[Dict[str, Any]],\n        file_path: Path\n    ) -> None:\n        with open(file_path, 'w', encoding='utf-8') as f:\n            json.dump(data, f, indent=2, ensure_ascii=False)\n\n\nclass CSVParser(FileParser):\n    \"\"\"Parse CSV files.\"\"\"\n    \n    def __init__(self, delimiter: str = ',') -> None:\n        self.delimiter = delimiter\n    \n    def parse(self, file_path: Path) -> List[Dict[str, Any]]:\n        with open(file_path, 'r', encoding='utf-8') as f:\n            reader = csv.DictReader(f, delimiter=self.delimiter)\n            return list(reader)\n    \n    def serialize(\n        self,\n        data: List[Dict[str, Any]],\n        file_path: Path\n    ) -> None:\n        if not data:\n            return\n        \n        with open(file_path, 'w', encoding='utf-8', newline='') as f:\n            fieldnames = data[0].keys()\n            writer = csv.DictWriter(\n                f,\n                fieldnames=fieldnames,\n                delimiter=self.delimiter\n            )\n            writer.writeheader()\n            writer.writerows(data)\n\n\nclass XMLParser(FileParser):\n    \"\"\"Parse XML files.\"\"\"\n    \n    def __init__(self, root_element: str, record_element: str) -> None:\n        self.root_element = root_element\n        self.record_element = record_element\n    \n    def parse(self, file_path: Path) -> List[Dict[str, Any]]:\n        tree = ET.parse(file_path)\n        root = tree.getroot()\n        \n        results = []\n        for record in root.findall(self.record_element):\n            results.append(self._element_to_dict(record))\n        \n        return results\n    \n    def _element_to_dict(self, element: ET.Element) -> Dict[str, Any]:\n        \"\"\"Convert XML element to dictionary.\"\"\"\n        result = {}\n        \n        for child in element:\n            result[child.tag] = child.text or \"\"\n        \n        return result\n    \n    def serialize(\n        self,\n        data: List[Dict[str, Any]],\n        file_path: Path\n    ) -> None:\n        root = ET.Element(self.root_element)\n        \n        for record in data:\n            record_elem = ET.SubElement(root, self.record_element)\n            for key, value in record.items():\n                child = ET.SubElement(record_elem, key)\n                child.text = str(value)\n        \n        tree = ET.ElementTree(root)\n        tree.write(file_path, encoding='utf-8', xml_declaration=True)\n\n\n# Factory for parsers\nclass ParserFactory:\n    \"\"\"Factory for creating file parsers.\"\"\"\n    \n    PARSERS = {\n        '.json': JSONParser,\n        '.csv': CSVParser,\n        '.xml': XMLParser,\n    }\n    \n    @classmethod\n    def get_parser(cls, file_path: Path) -> FileParser:\n        \"\"\"Get appropriate parser for file extension.\"\"\"\n        ext = file_path.suffix.lower()\n        \n        parser_class = cls.PARSERS.get(ext)\n        if not parser_class:\n            raise ValueError(f\"No parser for extension: {ext}\")\n        \n        return parser_class()\n    \n    @classmethod\n    def parse_file(cls, file_path: Path) -> List[Dict[str, Any]]:\n        \"\"\"Parse file using appropriate parser.\"\"\"\n        parser = cls.get_parser(file_path)\n        return parser.parse(file_path)\n```\n\n## Best Practices\n```\n1. Use context managers\n   with open() as f:\n       # File automatically closed\n\n2. Handle encoding explicitly\n   open(path, 'r', encoding='utf-8')\n\n3. Use streaming for large files\n   Don't load into memory\n\n4. Validate file types\n   Check magic numbers, not just extensions\n\n5. Use secure paths\n   Prevent path traversal\n\n6. Set proper permissions\n   chmod 644 for files, 755 for scripts\n\n7. Handle I\u002FO errors\n   Try-except around file operations\n\n8. Use temporary files\n   For processing sensitive data\n\n9. Clean up resources\n   Delete temp files, close handles\n\n10. Use async I\u002FO\n    For high-concurrency servers\n```\n",{"name":5,"license":15,"metadata":29,"description":7,"compatibility":22},{"audience":30,"category":31},"developers","utilities","main","2ea764e153842704d24a2e9aa4170441a7f03081",".opencode\u002Fskills\u002Ffile-handling","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito","https:\u002F\u002Fgithub.com\u002FNeuralBlitz","nuralnexus.org","Theoretical and Futuristic AI Nerd 🤓 ","2026-11-12 03:13:05",{"source":8,"skillName":5,"commands":41,"prompt":51,"zipAvailable":52},[42,45,48],{"tool":43,"command":44},"npx","npx skills add NeuralBlitz\u002FMito --skill file-handling",{"tool":46,"command":47},"bunx","bunx skills add NeuralBlitz\u002FMito --skill file-handling",{"tool":49,"command":50},"pnpm","pnpm dlx skills add NeuralBlitz\u002FMito --skill file-handling","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Ffile-handling\u002FSKILL.md",true,[],[55,71,83,96,104,129],{"skillNo":56,"name":57,"nameZh":6,"description":58,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":24},"01M6HAZSAQK1S27CEZYAYJTQDX","wireless-communications","Wireless systems, mobile networks, and 5G\u002F6G","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Fwireless-communications\u002FSKILL.md",[],[62,63,64,65,66,67,68,69,22,70],"communications","wireless communications","wireless","systems","engineering","networks","5G","students","mobile",{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":24},"01M6HAZFX6E8NK3WZWDX5YCKYY","websockets","WebSocket implementation and best practices","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Fwebassembly\u002Fwebsockets\u002FSKILL.md",[],[73,78,79,80,22,81,82,21],"websocket implementation","time","implementation","real-time","websocket",{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":24},"01M6HAZ6DAXBQ7QHXXM1EM7715","vulnerability-auditing","Vulnerability assessment and auditing","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Fvulnerability-auditing\u002FSKILL.md",[],[90,91,92,93,22,94,95],"vulnerability","vulnerability auditing","security","vulnerability assessment","cybersecurity","assessment",{"skillNo":97,"name":98,"nameZh":6,"description":99,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":100,"categories":101,"keywords":102,"publishedAt":24},"01M6HAZ3FKF3CS9Z3J96RVE2ZE","vulnerability-assessment","Finding and assessing security vulnerabilities","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Fvue\u002Fvulnerability-assessment\u002FSKILL.md",[],[93,90,95,92,103,22],"vulnerabilities",{"skillNo":105,"name":106,"nameZh":6,"description":107,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":108,"categories":109,"keywords":120,"publishedAt":24},"01M6HAYSHM6HKRKEHFP0SGZQX7","vlsi-design","Very-Large-Scale Integration circuit design and semiconductor engineering","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Fvlsi-design\u002FSKILL.md",[110,115],{"categoryNo":111,"categoryName":112,"taxonomyType":113,"taxonomyTypeDesc":114},"01JBSEEDCAT000000000000015","视觉设计","SCENARIO","使用场景",{"categoryNo":116,"categoryName":117,"taxonomyType":118,"taxonomyTypeDesc":119},"01JBSEEDCAT000000000000032","设计师","PROFESSION","适用职业",[121,122,123,124,125,66,126,22,127,69,128],"vlsi design","VLSI","design","hardware","integration","computer","scale","circuit",{"skillNo":130,"name":131,"nameZh":6,"description":132,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":133,"categories":134,"keywords":135,"publishedAt":24},"01M6HAYPQ30FFE2JXD7WQJ8R6C","unsupervised","Unsupervised learning concepts","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Fvisualization\u002Funsupervised\u002FSKILL.md",[],[131,136,22,137,138,139,140,141],"learning","intelligence","unsupervised learning","machine","concepts","machine-learning"]