{"id":768,"date":"2024-04-19T11:43:00","date_gmt":"2024-04-19T11:43:00","guid":{"rendered":"https:\/\/javigomez.org\/?p=768"},"modified":"2025-09-29T20:32:51","modified_gmt":"2025-09-29T20:32:51","slug":"07-04-python-archivos-de-texto-context-manager","status":"publish","type":"post","link":"https:\/\/javigomez.org\/index.php\/2024\/04\/19\/07-04-python-archivos-de-texto-context-manager\/","title":{"rendered":"07.04 Python \u2013 Archivos de texto Context Manager"},"content":{"rendered":"\n<p>__enter__ y __exit__ son m\u00e9todos especiales en Python que permiten a un objeto actuar como un &#8220;context manager&#8221;. Los context managers son objetos que definen un contexto de ejecuci\u00f3n y pueden utilizarse con la declaraci\u00f3n with para establecer y liberar recursos de manera adecuada.<\/p>\n\n\n\n<p>Cuando se utiliza la declaraci\u00f3n with, Python llamar\u00e1 autom\u00e1ticamente a los m\u00e9todos __enter__ y __exit__ del objeto. Esto es \u00fatil para garantizar que los recursos se inicialicen correctamente antes de entrar en el bloque de c\u00f3digo dentro del with y que se liberen adecuadamente al salir del bloque.<\/p>\n\n\n\n<p><strong>__<\/strong><strong>enter<\/strong><strong>__(<\/strong><strong>self<\/strong><strong>): <\/strong>Este m\u00e9todo se llama al entrar en el bloque with. Se utiliza para configurar y preparar los recursos o el contexto necesario antes de ejecutar el c\u00f3digo dentro del bloque with. Si el m\u00e9todo __enter__ devuelve alg\u00fan valor, este valor se asigna a la variable despu\u00e9s de la palabra clave as en la declaraci\u00f3n with.<\/p>\n\n\n\n<p><strong>__<\/strong><strong>exit<\/strong><strong>__(<\/strong><strong>self<\/strong><strong>, <\/strong><strong>exc_type<\/strong><strong>, <\/strong><strong>exc_value<\/strong><strong>, <\/strong><strong>traceback<\/strong><strong>): <\/strong>Este m\u00e9todo se llama al salir del bloque with, ya sea cuando se ejecut\u00f3 el c\u00f3digo dentro del bloque sin errores o cuando ocurri\u00f3 una excepci\u00f3n. Se utiliza para realizar tareas de limpieza y liberaci\u00f3n de recursos. Los par\u00e1metros exc_type, exc_value y traceback contienen informaci\u00f3n sobre cualquier excepci\u00f3n que haya ocurrido dentro del bloque with.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class miContexto:\n    def __init__(self,path):\n        self.path=path\n\n    def __enter__(self):\n        print(\"--Inicio contexto--\")\n        self.archivo=open(self.path,\"r\",encoding=\"utf-8\")\n        return self.archivo\n\n    def __exit__(self, exc_type, exc_val, exc_tb):\n        print(\"--Fin contexto--\")\n        if self.archivo:\n            self.archivo.close()\n\nwith miContexto(\"a.txt\") as archivo:\n    print(archivo.read())\n<\/code><\/pre>\n\n\n\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\"><div class=\"wp-block-embed__wrapper\">\n<iframe loading=\"lazy\" title=\"PYTHON U07 04 Archivos Context\" width=\"1200\" height=\"675\" src=\"https:\/\/www.youtube.com\/embed\/hHp9lIG5SRg?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe>\n<\/div><\/figure>\n","protected":false},"excerpt":{"rendered":"<p>__enter__ y __exit__ son m\u00e9todos especiales en Python que permiten a un objeto actuar como un &#8220;context manager&#8221;. Los context managers son objetos que definen &hellip; <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[9],"tags":[95,144,277],"class_list":["post-768","post","type-post","status-publish","format-standard","hentry","category-python","tag-context-manager","tag-ficheros","tag-python"],"_links":{"self":[{"href":"https:\/\/javigomez.org\/index.php\/wp-json\/wp\/v2\/posts\/768","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/javigomez.org\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/javigomez.org\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/javigomez.org\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/javigomez.org\/index.php\/wp-json\/wp\/v2\/comments?post=768"}],"version-history":[{"count":1,"href":"https:\/\/javigomez.org\/index.php\/wp-json\/wp\/v2\/posts\/768\/revisions"}],"predecessor-version":[{"id":846,"href":"https:\/\/javigomez.org\/index.php\/wp-json\/wp\/v2\/posts\/768\/revisions\/846"}],"wp:attachment":[{"href":"https:\/\/javigomez.org\/index.php\/wp-json\/wp\/v2\/media?parent=768"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/javigomez.org\/index.php\/wp-json\/wp\/v2\/categories?post=768"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/javigomez.org\/index.php\/wp-json\/wp\/v2\/tags?post=768"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}