{"id":2370,"date":"2023-07-22T13:54:32","date_gmt":"2023-07-22T13:54:32","guid":{"rendered":"https:\/\/statorials.org\/pt\/com-python-aberto\/"},"modified":"2023-07-22T13:54:32","modified_gmt":"2023-07-22T13:54:32","slug":"com-python-aberto","status":"publish","type":"post","link":"https:\/\/statorials.org\/pt\/com-python-aberto\/","title":{"rendered":"Como usar \u201cwith\u201d em python para abrir arquivos (incluindo exemplos)"},"content":{"rendered":"<p><\/p>\n<hr>\n<p><span style=\"color: #000000;\">Voc\u00ea pode usar a seguinte sintaxe para abrir um arquivo em Python, fazer algo com ele e depois fechar o arquivo:<\/span><\/p>\n<pre style=\"background-color: #ececec; font-size: 15px;\"> <strong>file = <span style=\"color: #008000;\">open<\/span> (' <span style=\"color: #ff0000;\">my_data.csv<\/span> ')\n\ndf = file. <span style=\"color: #3366ff;\">read<\/span> ()\n\n<span style=\"color: #008000;\">print<\/span> (df)\n\nfile. <span style=\"color: #3366ff;\">close<\/span> ()<\/strong><\/pre>\n<p> <span style=\"color: #000000;\">O problema dessa abordagem \u00e9 que \u00e9 muito f\u00e1cil esquecer de fechar o arquivo.<\/span><\/p>\n<p> <span style=\"color: #000000;\">Uma abordagem melhor \u00e9 usar <strong>open<\/strong> , que usa a seguinte sintaxe b\u00e1sica:<\/span><\/p>\n<pre style=\"background-color: #ececec; font-size: 15px;\"> <strong><span style=\"color: #008000;\">with<\/span> <span style=\"color: #008000;\">open<\/span> (' <span style=\"color: #ff0000;\">my_data.csv<\/span> ') <span style=\"color: #008000;\">as<\/span> file:\n\n   df = file. <span style=\"color: #3366ff;\">read<\/span> ()\n\n   <span style=\"color: #008000;\">print<\/span> (df)\n<\/strong><\/pre>\n<p> <span style=\"color: #000000;\">Usando essa abordagem, o arquivo com o qual voc\u00ea est\u00e1 trabalhando \u00e9 fechado automaticamente para que voc\u00ea n\u00e3o precise se lembrar de usar <strong>file.close()<\/strong> .<\/span><\/p>\n<p> <span style=\"color: #000000;\">Os exemplos a seguir mostram como usar <strong>open<\/strong> em diferentes cen\u00e1rios.<\/span><\/p>\n<h3> <span style=\"color: #000000;\"><strong>Exemplo 1: Use a instru\u00e7\u00e3o With para ler o arquivo<\/strong><\/span><\/h3>\n<p> <span style=\"color: #000000;\">O c\u00f3digo a seguir mostra como usar a instru\u00e7\u00e3o \u201cwith\u201d para ler um arquivo em Python e imprimir o conte\u00fado do arquivo:<\/span><\/p>\n<pre style=\"background-color: #ececec; font-size: 15px;\"> <strong><span style=\"color: #008000;\">with<\/span> <span style=\"color: #008000;\">open<\/span> (' <span style=\"color: #ff0000;\">my_data.csv<\/span> ') <span style=\"color: #008000;\">as<\/span> file:\n\n   df = file. <span style=\"color: #3366ff;\">read<\/span> ()\n\n   <span style=\"color: #008000;\">print<\/span> (df)\n\n,points, assists, rebounds\n0.11.5.6\n1,17,7,8\n2,16,7,8\n3,18,9,10\n4,22,12,14\n5,25,9,12\n6,26,9,12\n7,24,4,10\n8,29,8,11\n<\/strong><\/pre>\n<p> <span style=\"color: #000000;\">O conte\u00fado do arquivo \u00e9 impresso e o arquivo \u00e9 fechado automaticamente sem digitarmos <strong>file.close()<\/strong> .<\/span><\/p>\n<h3> <span style=\"color: #000000;\"><strong>Exemplo 2: Use a instru\u00e7\u00e3o With para escrever um arquivo<\/strong><\/span><\/h3>\n<p> <span style=\"color: #000000;\">O c\u00f3digo a seguir mostra como usar a instru\u00e7\u00e3o \u201cwith\u201d para escrever texto em um arquivo:<\/span><\/p>\n<pre style=\"background-color: #ececec; font-size: 15px;\"> <strong><span style=\"color: #008000;\">with<\/span> <span style=\"color: #008000;\">open<\/span> (' <span style=\"color: #ff0000;\">data_out.csv<\/span> ', ' <span style=\"color: #ff0000;\">w<\/span> ') <span style=\"color: #008000;\">as<\/span> file:\n\n    file. <span style=\"color: #3366ff;\">write<\/span> (' <span style=\"color: #ff0000;\">Some text to write to CSV file<\/span> ')\n<\/strong><\/pre>\n<p> <span style=\"color: #000000;\"><span style=\"color: #000000;\">Observe que o &#8216; <strong>w<\/strong> &#8216; na instru\u00e7\u00e3o <strong>open()<\/strong> diz ao Python para usar o modo &#8216;grava\u00e7\u00e3o&#8217; com o arquivo em vez do modo de leitura.<\/span><\/span><\/p>\n<h3> <span style=\"color: #000000;\"><strong>Exemplo 3: Use a instru\u00e7\u00e3o With para ler e gravar arquivos<\/strong><\/span><\/h3>\n<p> <span style=\"color: #000000;\">Tamb\u00e9m podemos abrir v\u00e1rios arquivos de uma vez em uma \u00fanica instru\u00e7\u00e3o \u201cwith\u201d.<\/span><\/p>\n<p> <span style=\"color: #000000;\">O c\u00f3digo a seguir mostra como usar a instru\u00e7\u00e3o \u201cwith\u201d para abrir dois arquivos, ler o conte\u00fado de um arquivo e, em seguida, gravar o conte\u00fado do primeiro arquivo no segundo arquivo:<\/span><\/p>\n<pre style=\"background-color: #ececec; font-size: 15px;\"> <strong><span style=\"color: #008000;\">with<\/span> <span style=\"color: #008000;\">open<\/span> (' <span style=\"color: #ff0000;\">my_data.csv<\/span> ', ' <span style=\"color: #ff0000;\">r<\/span> ') <span style=\"color: #008000;\">as<\/span> infile, <span style=\"color: #008000;\">open<\/span> (' <span style=\"color: #ff0000;\">data_out.csv<\/span> ', ' <span style=\"color: #ff0000;\">w<\/span> ') <span style=\"color: #008000;\">as<\/span> outfile:\n    <span style=\"color: #008000;\">for<\/span> line <span style=\"color: #008000;\">in<\/span> infile:\n        outfile. <span style=\"color: #3366ff;\">write<\/span> (line)<\/strong><\/pre>\n<p> <span style=\"color: #000000;\">Se navegarmos at\u00e9 o local onde escrevemos \u201cdata_out.csv\u201d, poderemos ent\u00e3o visualizar o conte\u00fado do arquivo:<\/span> <\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\" wp-image-21428 aligncenter\" src=\"https:\/\/statorials.org\/wp-content\/uploads\/2023\/08\/avec1.png\" alt=\"\" width=\"627\" height=\"302\" srcset=\"\" sizes=\"auto, \"><\/p>\n<p> <span style=\"color: #000000;\">Observe que podemos usar a fun\u00e7\u00e3o <strong>open()<\/strong> para abrir quantos arquivos quisermos em uma \u00fanica instru\u00e7\u00e3o \u201cwith\u201d.<\/span><\/p>\n<h3> <span style=\"color: #000000;\"><strong>Recursos adicionais<\/strong><\/span><\/h3>\n<p> <span style=\"color: #000000;\">Os tutoriais a seguir explicam como realizar outras opera\u00e7\u00f5es comuns em Python:<\/span><\/p>\n<p> <a href=\"https:\/\/statorials.org\/pt\/pandas-leem-csv\/\" target=\"_blank\" rel=\"noopener\">Como ler arquivos CSV com Pandas<\/a><br \/> <a href=\"https:\/\/statorials.org\/pt\/pandas-leem-excel\/\" target=\"_blank\" rel=\"noopener\">Como ler arquivos Excel com Pandas<\/a><br \/> <a href=\"https:\/\/statorials.org\/pt\/pandas-leem-arquivo-de-texto\/\" target=\"_blank\" rel=\"noopener\">Como ler arquivos de texto com Pandas<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Voc\u00ea pode usar a seguinte sintaxe para abrir um arquivo em Python, fazer algo com ele e depois fechar o arquivo: file = open (&#8216; my_data.csv &#8216;) df = file. read () print (df) file. close () O problema dessa abordagem \u00e9 que \u00e9 muito f\u00e1cil esquecer de fechar o arquivo. Uma abordagem melhor \u00e9 [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[11],"tags":[],"class_list":["post-2370","post","type-post","status-publish","format-standard","hentry","category-guia"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v21.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Como usar \u201cwith\u201d em Python para abrir arquivos (incluindo exemplos) - Estatologia<\/title>\n<meta name=\"description\" content=\"Este tutorial explica como usar a instru\u00e7\u00e3o \u201cwith\u201d em Python para abrir arquivos, com v\u00e1rios exemplos.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/statorials.org\/pt\/com-python-aberto\/\" \/>\n<meta property=\"og:locale\" content=\"pt_PT\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Como usar \u201cwith\u201d em Python para abrir arquivos (incluindo exemplos) - Estatologia\" \/>\n<meta property=\"og:description\" content=\"Este tutorial explica como usar a instru\u00e7\u00e3o \u201cwith\u201d em Python para abrir arquivos, com v\u00e1rios exemplos.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/statorials.org\/pt\/com-python-aberto\/\" \/>\n<meta property=\"og:site_name\" content=\"Statorials\" \/>\n<meta property=\"article:published_time\" content=\"2023-07-22T13:54:32+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/statorials.org\/wp-content\/uploads\/2023\/08\/avec1.png\" \/>\n<meta name=\"author\" content=\"Dr. benjamim anderson\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Escrito por\" \/>\n\t<meta name=\"twitter:data1\" content=\"Dr. benjamim anderson\" \/>\n\t<meta name=\"twitter:label2\" content=\"Tempo estimado de leitura\" \/>\n\t<meta name=\"twitter:data2\" content=\"2 minutos\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/statorials.org\/pt\/com-python-aberto\/\",\"url\":\"https:\/\/statorials.org\/pt\/com-python-aberto\/\",\"name\":\"Como usar \u201cwith\u201d em Python para abrir arquivos (incluindo exemplos) - Estatologia\",\"isPartOf\":{\"@id\":\"https:\/\/statorials.org\/pt\/#website\"},\"datePublished\":\"2023-07-22T13:54:32+00:00\",\"dateModified\":\"2023-07-22T13:54:32+00:00\",\"author\":{\"@id\":\"https:\/\/statorials.org\/pt\/#\/schema\/person\/e08f98e8db95e0aa9c310e1b27c9c666\"},\"description\":\"Este tutorial explica como usar a instru\u00e7\u00e3o \u201cwith\u201d em Python para abrir arquivos, com v\u00e1rios exemplos.\",\"breadcrumb\":{\"@id\":\"https:\/\/statorials.org\/pt\/com-python-aberto\/#breadcrumb\"},\"inLanguage\":\"pt-PT\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/statorials.org\/pt\/com-python-aberto\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/statorials.org\/pt\/com-python-aberto\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Lar\",\"item\":\"https:\/\/statorials.org\/pt\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Como usar \u201cwith\u201d em python para abrir arquivos (incluindo exemplos)\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/statorials.org\/pt\/#website\",\"url\":\"https:\/\/statorials.org\/pt\/\",\"name\":\"Statorials\",\"description\":\"O seu guia para a literacia estat\u00edstica!\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/statorials.org\/pt\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"pt-PT\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/statorials.org\/pt\/#\/schema\/person\/e08f98e8db95e0aa9c310e1b27c9c666\",\"name\":\"Dr. benjamim anderson\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"pt-PT\",\"@id\":\"https:\/\/statorials.org\/pt\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/statorials.org\/pt\/wp-content\/uploads\/2023\/10\/Dr.-Benjamin-Anderson-96x96.jpg\",\"contentUrl\":\"https:\/\/statorials.org\/pt\/wp-content\/uploads\/2023\/10\/Dr.-Benjamin-Anderson-96x96.jpg\",\"caption\":\"Dr. benjamim anderson\"},\"description\":\"Ol\u00e1, sou Benjamin, um professor aposentado de estat\u00edstica que se tornou professor dedicado na Statorials. Com vasta experi\u00eancia e conhecimento na \u00e1rea de estat\u00edstica, estou empenhado em compartilhar meu conhecimento para capacitar os alunos por meio de Statorials. Saber mais\",\"sameAs\":[\"https:\/\/statorials.org\/pt\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Como usar \u201cwith\u201d em Python para abrir arquivos (incluindo exemplos) - Estatologia","description":"Este tutorial explica como usar a instru\u00e7\u00e3o \u201cwith\u201d em Python para abrir arquivos, com v\u00e1rios exemplos.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/statorials.org\/pt\/com-python-aberto\/","og_locale":"pt_PT","og_type":"article","og_title":"Como usar \u201cwith\u201d em Python para abrir arquivos (incluindo exemplos) - Estatologia","og_description":"Este tutorial explica como usar a instru\u00e7\u00e3o \u201cwith\u201d em Python para abrir arquivos, com v\u00e1rios exemplos.","og_url":"https:\/\/statorials.org\/pt\/com-python-aberto\/","og_site_name":"Statorials","article_published_time":"2023-07-22T13:54:32+00:00","og_image":[{"url":"https:\/\/statorials.org\/wp-content\/uploads\/2023\/08\/avec1.png"}],"author":"Dr. benjamim anderson","twitter_card":"summary_large_image","twitter_misc":{"Escrito por":"Dr. benjamim anderson","Tempo estimado de leitura":"2 minutos"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/statorials.org\/pt\/com-python-aberto\/","url":"https:\/\/statorials.org\/pt\/com-python-aberto\/","name":"Como usar \u201cwith\u201d em Python para abrir arquivos (incluindo exemplos) - Estatologia","isPartOf":{"@id":"https:\/\/statorials.org\/pt\/#website"},"datePublished":"2023-07-22T13:54:32+00:00","dateModified":"2023-07-22T13:54:32+00:00","author":{"@id":"https:\/\/statorials.org\/pt\/#\/schema\/person\/e08f98e8db95e0aa9c310e1b27c9c666"},"description":"Este tutorial explica como usar a instru\u00e7\u00e3o \u201cwith\u201d em Python para abrir arquivos, com v\u00e1rios exemplos.","breadcrumb":{"@id":"https:\/\/statorials.org\/pt\/com-python-aberto\/#breadcrumb"},"inLanguage":"pt-PT","potentialAction":[{"@type":"ReadAction","target":["https:\/\/statorials.org\/pt\/com-python-aberto\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/statorials.org\/pt\/com-python-aberto\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Lar","item":"https:\/\/statorials.org\/pt\/"},{"@type":"ListItem","position":2,"name":"Como usar \u201cwith\u201d em python para abrir arquivos (incluindo exemplos)"}]},{"@type":"WebSite","@id":"https:\/\/statorials.org\/pt\/#website","url":"https:\/\/statorials.org\/pt\/","name":"Statorials","description":"O seu guia para a literacia estat\u00edstica!","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/statorials.org\/pt\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"pt-PT"},{"@type":"Person","@id":"https:\/\/statorials.org\/pt\/#\/schema\/person\/e08f98e8db95e0aa9c310e1b27c9c666","name":"Dr. benjamim anderson","image":{"@type":"ImageObject","inLanguage":"pt-PT","@id":"https:\/\/statorials.org\/pt\/#\/schema\/person\/image\/","url":"https:\/\/statorials.org\/pt\/wp-content\/uploads\/2023\/10\/Dr.-Benjamin-Anderson-96x96.jpg","contentUrl":"https:\/\/statorials.org\/pt\/wp-content\/uploads\/2023\/10\/Dr.-Benjamin-Anderson-96x96.jpg","caption":"Dr. benjamim anderson"},"description":"Ol\u00e1, sou Benjamin, um professor aposentado de estat\u00edstica que se tornou professor dedicado na Statorials. Com vasta experi\u00eancia e conhecimento na \u00e1rea de estat\u00edstica, estou empenhado em compartilhar meu conhecimento para capacitar os alunos por meio de Statorials. Saber mais","sameAs":["https:\/\/statorials.org\/pt"]}]}},"yoast_meta":{"yoast_wpseo_title":"","yoast_wpseo_metadesc":"","yoast_wpseo_canonical":""},"_links":{"self":[{"href":"https:\/\/statorials.org\/pt\/wp-json\/wp\/v2\/posts\/2370","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/statorials.org\/pt\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/statorials.org\/pt\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/statorials.org\/pt\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/statorials.org\/pt\/wp-json\/wp\/v2\/comments?post=2370"}],"version-history":[{"count":0,"href":"https:\/\/statorials.org\/pt\/wp-json\/wp\/v2\/posts\/2370\/revisions"}],"wp:attachment":[{"href":"https:\/\/statorials.org\/pt\/wp-json\/wp\/v2\/media?parent=2370"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/statorials.org\/pt\/wp-json\/wp\/v2\/categories?post=2370"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/statorials.org\/pt\/wp-json\/wp\/v2\/tags?post=2370"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}