Leitura e Escrita em Arquivos

No Python, se quisermos abrir um arquivo de texto puro para leitura, temos várias construções possíveis. Porém, a mais utilizada e que é, em geral, mais simples, é a seguinte:


In [1]:
import os
diretorio = os.path.join(os.getcwd(), "..","exemplos/exemplo_2")
with open(os.path.join(diretorio,"file1.txt"), "r") as arquivo:
    numlinhas = 0
    for line in arquivo:
        numlinhas += 1
        
print(numlinhas)


131

Atenção: Os exemplos foram formulados no Linux; se você estiver usando Windows ou MacOS, talvez seja necessário alterar os separadores de diretórios/arquivos para uma contrabarra, por exemplo.

O bloco with open(...), quando executado, abre o arquivo com a opção escohida (no caso acima, 'r', pois queremos apenas ler o arquivo), e automaticamente fecha o arquivo quando é concluido.

Observe que as linhas do arquivo podem ser acessadas diretamente, uma a uma, através de um bloco for:


In [2]:
with open(os.path.join(diretorio,"file1.txt"), "r") as meuarquivo:
    for linha in meuarquivo:
        print(linha)


dom set 11 18:10:54 BRT 2016 

LaDo9ltXdFz7dQBvg52Kqy2jTybecYal2hg3+RdUEzq67KWnaU59RGrRfndSOSq7YMbjQd3tgUVp

sAeUFfN0Peu3goZbdV5ycNsv2zNpfAT0i8RSiDd/IMSGuvhTdLzkij1JCDDufn+qiUikZTXkOz8s

rb6bysNf65RZEVfAEWXqiwbziSri3cTu6k62IhXRdiglX2KmFQeckYjfiHZztm6ijO2kgsytdWuY

xI/g5W/DOh0AujX453TU4KFw5wjxj0EoAlM8FGMbzU1JUxONuUZd1b1wbEaQlEN69m9GV7qLTiRR

4f0J/xobEQip7QsavNDjAuVhDZNpWpE4HFJu93W6FzQrp/274RgUghF5fmKW7APvG23+AaeN21To

7aDitX3gQM8O/AE00tZh7C9+N8j/CKq7esoFsOMQN9SUvx+PxL87HbeF2xhqkrnabiQABT2r9fR8

TW0EbnM6iZTnLsG6X0fF4/Zk3dRa9cw/fhXCvWbskamgSj4jAw5gGYLFk+5ZJsSr1ElTTU74vqef

tThh4LLCTGQXFSdDNpqwaUuJY0/BAYk7Zlo04f4CImeO8FOm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4CwTTVET7hlJFW0vjCbsAYQFZ1V2swZOZ91xA+Ih99cf7Xb

l8cW9i1IhUiiljz0ybt1RmiPumzGDrCpb2zH1urvFsX0AIhdXh5K+DKKAwYDAg/FycUx9x8MXBYo

MD9An7I3L2MCJU+9nzhvZxPx066rUKpOoGb2b/LS0aXV6GuS3AAPCQIoQa+lrYNxE6vn31dXOgzV

DkzA+SzVeCCATVoSDgrE2IdWY9rNeclOZMV0fbjutz/VvGqMDwdwmJmIyUDcBGBAv20dm90fwG+w

OvKlPaqwwFgQGmzDZtwBGOv8Hd0efXvvVcskl49b0oRJsEN6fmlZ7ql1rpfvncFrHUXqnMe+nC7w

JGJgKCdRoMXr8svptiRIiWIQTR3hdiKF1FVZDiFxFIYHyEwEF8rc79y5oJbI6Qa4YxEt/tJt7I8I

4L0EeffPhUogHWY+fMRZjhRxajK/UkHYKoMPF1LRa5KHWipr0R6HxZaj5RApsbWKZHn57OKKQ2qP

727xeD/W1zTnvIb11Op2XBgE6E1XRKW+krduN0O4JCh6I5+NAXAgBxIcAt3M6N6AJ/l1DOqw6EDi

xEen1j9HYe/FFmaD0CriNVF2l703xudJUDjB1BAiucEv98IjRavwnekdoFL8fPFmTEW56W940zwq

3LkEMWdzeT408mhQRve/T3YCo3kxwfZNMZJ1o+XzjYLGjQzgvEgsPAMmFTG/HlHNtEWrz5786guu

HV/MwMV6BirkxlUTxCb3uOleVvmnrXk4duHbpu/F3xFiNhNTpoPLRQ1M70fGq+m4R8I

Exemplo

Tentar encontrar uma string específica (no nosso caso, "sf") dentro do arquivo file1.txt


In [5]:
string = "sf"
b = []
with open(os.path.join(diretorio,"file1.txt"),"r") as arquivo:
    for line in arquivo:
        if string in line:
            b.append(line.rstrip("\n"))

Neste momento, a lista b contém todas as linhas do arquivo que continham a string desejada:


In [6]:
print(b)


['gWaEQDuKFwfdsfZVei8H/et86m5RTYa/8gzW04KZqrhX3mYbYNMSlorHMNzL7JGahi+5hihEE0fX', 'uxnZz/a4oaKhtcrtLdESS/i4PuFxdy/WegCcd8v0Qza2FWrVUQq6kDHNsfu1T5p/mKNBv9FcNWPE']

Para alguns casos específicos, pode ser interessante carregar um arquivo completo na memória. Para isso, usamos


In [7]:
with open(os.path.join(diretorio,"file1.txt"),"r") as arquivo:
    conteudo = arquivo.read()
    
print(conteudo)


dom set 11 18:10:54 BRT 2016 
LaDo9ltXdFz7dQBvg52Kqy2jTybecYal2hg3+RdUEzq67KWnaU59RGrRfndSOSq7YMbjQd3tgUVp
sAeUFfN0Peu3goZbdV5ycNsv2zNpfAT0i8RSiDd/IMSGuvhTdLzkij1JCDDufn+qiUikZTXkOz8s
rb6bysNf65RZEVfAEWXqiwbziSri3cTu6k62IhXRdiglX2KmFQeckYjfiHZztm6ijO2kgsytdWuY
xI/g5W/DOh0AujX453TU4KFw5wjxj0EoAlM8FGMbzU1JUxONuUZd1b1wbEaQlEN69m9GV7qLTiRR
4f0J/xobEQip7QsavNDjAuVhDZNpWpE4HFJu93W6FzQrp/274RgUghF5fmKW7APvG23+AaeN21To
7aDitX3gQM8O/AE00tZh7C9+N8j/CKq7esoFsOMQN9SUvx+PxL87HbeF2xhqkrnabiQABT2r9fR8
TW0EbnM6iZTnLsG6X0fF4/Zk3dRa9cw/fhXCvWbskamgSj4jAw5gGYLFk+5ZJsSr1ElTTU74vqef
tThh4LLCTGQXFSdDNpqwaUuJY0/BAYk7Zlo04f4CImeO8FOmRE9EVEVJ4hvxuWMVXrdQYXC2LDat
19dLLghqwJFBckWBY9rueUIhrylvbCms6IHcWVXIjkzTIJnKimmp0G+w1NW3gXVMZMR2J9Qr3oKG
o6cP4e8YgqMqCbL3PlA2hpgyE3BixC0cIOd7yL4dbPKibg2LwEPSJDMtsrHKfG5OrAY5ZuAg67ou
iy1yS5SQ4vYhmi6iKjsyMqCqlVYiA40DsySCWKNRHU2BEwN64yrFTbBeBA1a09rdqKATZFXkLCnA
30YtUf6GZtua13EYWDn0/nDuZyIwZYYlWsiHbX5TK5in7NmXC12ls4F52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cskl49b0oRJsEN6fmlZ7ql1rpfvncFrHUXqnMe+nC7w
JGJgKCdRoMXr8svptiRIiWIQTR3hdiKF1FVZDiFxFIYHyEwEF8rc79y5oJbI6Qa4YxEt/tJt7I8I
4L0EeffPhUogHWY+fMRZjhRxajK/UkHYKoMPF1LRa5KHWipr0R6HxZaj5RApsbWKZHn57OKKQ2qP
727xeD/W1zTnvIb11Op2XBgE6E1XRKW+krduN0O4JCh6I5+NAXAgBxIcAt3M6N6AJ/l1DOqw6EDi
xEen1j9HYe/FFmaD0CriNVF2l703xudJUDjB1BAiucEv98IjRavwnekdoFL8fPFmTEW56W940zwq
3LkEMWdzeT408mhQRve/T3YCo3kxwfZNMZJ1o+XzjYLGjQzgvEgsPAMmFTG/HlHNtEWrz5786guu
HV/MwMV6BirkxlUTxCb3uOleVvmnrXk4duHbpu/F3xFiNhNTpoPLRQ1M70fGq+m4R8I

Também podemos usar o comando readline:


In [8]:
with open(os.path.join(diretorio,"file1.txt"), "r") as arquivo:
    print(arquivo.readline())


dom set 11 18:10:54 BRT 2016 

Sem argumentos, ele lê a próxima linha do arquivo; isto quer dizer que se ele é executado diversas vezes em sequência, com o arquivo aberto, ele lê a cada vez que é executado uma das linhas do arquivo.


In [9]:
with open(os.path.join(diretorio,"file1.txt"), "r") as arquivo:
    for i in range(0,5):
        print(arquivo.readline())


dom set 11 18:10:54 BRT 2016 

LaDo9ltXdFz7dQBvg52Kqy2jTybecYal2hg3+RdUEzq67KWnaU59RGrRfndSOSq7YMbjQd3tgUVp

sAeUFfN0Peu3goZbdV5ycNsv2zNpfAT0i8RSiDd/IMSGuvhTdLzkij1JCDDufn+qiUikZTXkOz8s

rb6bysNf65RZEVfAEWXqiwbziSri3cTu6k62IhXRdiglX2KmFQeckYjfiHZztm6ijO2kgsytdWuY

xI/g5W/DOh0AujX453TU4KFw5wjxj0EoAlM8FGMbzU1JUxONuUZd1b1wbEaQlEN69m9GV7qLTiRR

Exemplo

Ler a 10a linha do arquivo, de três maneiras diferentes:


In [11]:
with open(os.path.join(diretorio,"file1.txt"), "r") as arquivo:
    for i in range(0,10):
        linha = arquivo.readline()
        if i == 9:
            print(linha)


19dLLghqwJFBckWBY9rueUIhrylvbCms6IHcWVXIjkzTIJnKimmp0G+w1NW3gXVMZMR2J9Qr3oKG


In [12]:
with open(os.path.join(diretorio,"file1.txt"), "r") as arquivo:
    i = 0
    for linha in arquivo:
        if i == 9:
            print(linha)
        i = i + 1


19dLLghqwJFBckWBY9rueUIhrylvbCms6IHcWVXIjkzTIJnKimmp0G+w1NW3gXVMZMR2J9Qr3oKG


In [13]:
with open(os.path.join(diretorio,"file1.txt"), "r") as arquivo:
    conteudo = list(arquivo.read().split("\n"))
    
print(conteudo[9])


19dLLghqwJFBckWBY9rueUIhrylvbCms6IHcWVXIjkzTIJnKimmp0G+w1NW3gXVMZMR2J9Qr3oKG

Exemplo:

Ler a primeira linha de cada arquivo de um diretorio e escrever o resultado em outro arquivo.

Primeiro, usamos uma list comprehension para obtermos uma lista dos arquivos no diretorio em que estamos interessados, mas queremos excluir o arquivo teste.txt e queremos que os arquivos estejam listados com seu caminho completo.


In [14]:
print([os.path.join(diretorio,item) for item in os.listdir(diretorio) if item != "teste.txt"])


['/home/melissa/Dropbox/trabalho/2016.2/oceanobiopython/Notebooks/../exemplos/exemplo_2/file5.txt', '/home/melissa/Dropbox/trabalho/2016.2/oceanobiopython/Notebooks/../exemplos/exemplo_2/file2.txt', '/home/melissa/Dropbox/trabalho/2016.2/oceanobiopython/Notebooks/../exemplos/exemplo_2/file1.txt', '/home/melissa/Dropbox/trabalho/2016.2/oceanobiopython/Notebooks/../exemplos/exemplo_2/file4.txt', '/home/melissa/Dropbox/trabalho/2016.2/oceanobiopython/Notebooks/../exemplos/exemplo_2/file3.txt']

In [15]:
lista = [os.path.join(diretorio,item) for item in os.listdir(diretorio) if item != "teste.txt"]

In [16]:
lista


Out[16]:
['/home/melissa/Dropbox/trabalho/2016.2/oceanobiopython/Notebooks/../exemplos/exemplo_2/file5.txt',
 '/home/melissa/Dropbox/trabalho/2016.2/oceanobiopython/Notebooks/../exemplos/exemplo_2/file2.txt',
 '/home/melissa/Dropbox/trabalho/2016.2/oceanobiopython/Notebooks/../exemplos/exemplo_2/file1.txt',
 '/home/melissa/Dropbox/trabalho/2016.2/oceanobiopython/Notebooks/../exemplos/exemplo_2/file4.txt',
 '/home/melissa/Dropbox/trabalho/2016.2/oceanobiopython/Notebooks/../exemplos/exemplo_2/file3.txt']

Agora, vamos ler apenas a primeira linha de cada arquivo:


In [17]:
for item in lista:
    with open(item,"r") as arquivo:
        print(arquivo.readline())


qui set 08 22:42:51 BRT 2016

qua set 07 11:00:22 BRT 2016

dom set 11 18:10:54 BRT 2016 

seg ago 29 13:19:03 BRT 2016

ter ago 16 08:24:00 BRT 2016


In [18]:
with open("resumo.txt", "w") as arquivo_saida:
    for item in lista:
        with open(item,"r") as arquivo:
            arquivo_saida.write(arquivo.readline()+"\n")

Agora, vamos desfazer o exemplo:


In [19]:
os.remove("resumo.txt")

Alguns links importantes

Documentação sobre funções built-in: https://docs.python.org/3/library/functions.html

Documentação oficial: https://docs.python.org/3

(Fim da Aula 3, ministrada em 20/09/2016)