kb.erickguedes.com
Python: De Noob a Hero

Manipulação de Arquivos e Exceções

Aula 6 de 10

Arquivos

# Escrita
with open("dados.txt", "w", encoding="utf-8") as f:
    f.write("Linha 1\n")
    f.write("Linha 2\n")

# Leitura
with open("dados.txt", "r", encoding="utf-8") as f:
    conteudo = f.read()          # tudo
    linhas = f.readlines()       # lista de linhas
    for linha in f:              # iterar (eficiente)
        print(linha.strip())

# Append
with open("log.txt", "a") as f:
    f.write("Nova entrada\n")

# JSON
import json

dados = {"nome": "Maria", "idade": 30}
with open("dados.json", "w") as f:
    json.dump(dados, f, indent=2)

with open("dados.json") as f:
    carregado = json.load(f)

Tratamento de Exceções

try:
    numero = int(input("Digite um número: "))
    resultado = 10 / numero
    print(f"Resultado: {resultado}")
except ValueError:
    print("Isso não é um número!")
except ZeroDivisionError:
    print("Divisão por zero!")
except Exception as e:
    print(f"Erro inesperado: {e}")
else:
    print("Sem erros!")          # executa se não houve exceção
finally:
    print("Sempre executa")      # cleanup

# Levantar exceções
def sacar(saldo, valor):
    if valor <= 0:
        raise ValueError("Valor deve ser positivo")
    if valor > saldo:
        raise ValueError("Saldo insuficiente")
    return saldo - valor

Context Managers Personalizados

class TimerContext:
    def __enter__(self):
        import time
        self.start = time.time()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        import time
        duracao = time.time() - self.start
        print(f"Levou {duracao:.3f}s")

with TimerContext():
    sum(range(1000000))

# Com contextlib
from contextlib import contextmanager

@contextmanager
def timer():
    import time
    start = time.time()
    yield
    print(f"Levou {time.time() - start:.3f}s")

with timer():
    sum(range(1000000))

Sempre use with para manipular arquivos — ele garante o fechamento mesmo em caso de erro. Trate exceções específicas, nunca except Exception sem necessidade.