Vous êtes sur la page 1sur 15

Manipulando arquivos com Python

Incio

Artigos

Manipulando arquivos com Python

Incio

Artigos

Cursos
o

Python From Scratch

Newsletter

Sobre

Contato

Publicado por: Julio Cesar Eiras Melanda 2 anos, 10 meses atrs


(0 Comentrios)
Boa noite pessoal!

Seguindo algumas sugestes, hoje vamos falar de um tema que acidentalmente foi
esquecido por aqui: Manipulao de arquivos!

Veremos aqui as formas mais simples (e frequentes) de ler e escrever em arquivos.

Comece criando um arquivo txt com algum texto dentro, especialmente se este tiver ao
menos umas 10 linhas.

Usaremos arquivos de texto por serem os mais simples, mas estes mtodos servem para
qualquer tipo de arquivo.

Como exemplo aqui pegarei uma letra de msica:

Well you done done me and you bet I felt it


I tried to be chill but you're so hot that I melted
I fell right through the cracks, now I'm trying to get back
Before the cool done run out I'll be giving it my bestest
And nothing's going to stop me but divine intervention
I reckon it's again my turn to win some or learn some
But I won't hesitate no more, no more
It cannot wait, I'm yours
Well open up your mind and see like me
Open up your plans and damn you're free

Chamei o arquivo de musica.txt.

agora, no terminal v at o diretrio onde est seu arquivo e abra o interpretador Python.

Abra o arquivo com o comando:

>>> arquivo = open('musica.txt', 'r')

Agora voc ter um objeto file na varivel arquivo. Observe que o parmetro 'r' indica que
est abrindo o arquivo somente para leitura.

Execute ento o seguinte comando:

>>> arquivo.read()

Voc ver que foi retornado todo o contedo do arquivo em uma s string.
Leia novamente o arquivo:

>>> arquivo = open('musica.txt', 'r')

Execute o comando:

>>> arquivo. readlines()

Agora, o arquivo soi lido totalmente, porm desta vez como uma lista de strings, com uma
string para cada linha.
Leia o arquivo mais uma vez:

>>> arquivo = open('musica.txt', 'r')

Execute:

>>> arquivo.readline()

Seu retorno desta vez somente a primeira linha do arquivo.


Executando novamente, voc receber a segunda linha e assim por diante.
Experimente:

>>> arquivo.readline()

Cada um destes mtodos pode receber parmetros, mas o artigo se alongaria


demasiadamente se fosse explicar cada possibilidade. Os comandos feitos assim j so
suficientes para suprir uma grande parte da necessidade que voc pode encontrar de
leitura de arquivos.

Agora veremos as duas possibilidades de escrita em arquivos.

Feche o arquio e leia novamente o arquivo:

>>> arquivo.close()
>>> arquivo = open('musica.txt', 'w')

Note que desta vez trocamos o 'r' por 'w', pois iremos abrir o arquivo para escrita.
Execute:

>>> arquivo.write('Qualquer coisa')


>>> arquivo.close()

Todo o contedo do seu arquivo ser substituido por 'Qualquer coisa'. Para a alterao

acontecer, s vezes imprescindvel fechar o arquivo, ento, devemos sempre fazer isto
para garantir.

Caso voc no queira sobrescrever o contedo, mas adicionar, deve ler o contedo para
uma varivel, adicionar a nova string e somente ento escrever. Assim:

>>> arquivo = open('musica.txt', 'r')


>>> texto = arquivo.readlines()
>>> texto.append('Nova linha')
>>> arquivo = open('musica.txt', 'w')
>>> arquivo.writelines(texto)
>>> arquivo.close()

Neste bloco, abrimos o arquivo para leitura, salvamos seu contedo como uma lista de
strings dentro de uma varivel, adicionamos uma nova string a esta lista e ento
escrevemos a lista no arquivo.

Escrita e leitura de arquivos uma das tarefas mais importantes a se realizar com uma
linguagem de programao, ento brinque bastante, perceba as nuances e use os
comandos dir() e help() para entender melhor os mtodos e objetos envolvidos.

Espero que tenham gostado de ver como simples e direta a manipulao de arquivos em
Python!

Dvidas e sugestes por email ou nos comentrios!

Muito obrigado, e at a prxima!

Tags:

Arquivos

Tutorial

Programao Bsica

Manipulando arquivos

Uma coisa bem interessante em Python a manipulao de arquivos,


que bastante simples. Vamos tomar como exemplo o arquivo
'texto.txt' :
>>> f = open( '/home/igor/texto.txt', 'w')
a funo open possui trs argumentos: nome do arquivo, modo e
buffer, sendo os dois ultimos opcionais. No exemplo acima, eu usei o
nome e o modo 'w'. Vamos falar um pouco sobre os possiveis modos:
Existem trs tipos basicos de modos: 'w', 'r', 'a'. Write ('w') usado
para escrever algo no arquivo, apagando o que j havia nele, e caso
o arquivo ainda no exista, ele ser criado. Mas e se eu quiser
apenas adicionar um texto sem apagar o que ja tinha la? Ai estamos
falando no modo 'a' (append, pra quem conhece os metodos de listas
isso deve ser familiar), agora todo o texto escrito ser adicionado no
final do que tinha anteriormente (lembrando que o texto inserido
no formato string, no tem nada a ver com listas), nesse caso, se o
arquivo tambm no existir ele ser criado sem problemas. E como
era de se esperar, 'r' usado para ler um arquivo j existente.
Mas ainda tem alguns modificadores de modos:
>>> f = open('/home/igor/texto.txt','r+')
quando um '+' inserido no final de qualquer modo, ele possibilita
tanto a leitura quanto a escrita.
>>> f = open('/home/igor/texto.txt','rb')
Esse 'b', adicionado ao lado de algum modo, manuseia o arquivo em

binario, e no em texto, como o padro.


Caso no seja especificado nenhum modo na funo open, sera
atribuido 'r' (read), que o padro.
O terceiro argumento, tambm opcional o buffer, caso seja 0 ou
False, no haver buffer, ou seja, toda vez que o arquivo for ser
utilizado, ele ser manuseado diretamente do disco rigido; ja se for 1
ou True, ento haver buffer, o arquivo ser manuseado da memoria,
o que deixa o processo mais rpido. Caso for declarado um numero
maior que 1, esse numero indicara o nivel de buffer (em bytes).
Mas agora vamos ao que interessa, escrever:
>>> f = open('/home/igor/Python/texto','w')
>>> f.write('Ola Mundo!')
Como o modo padro texto, no necessrio a extenso .txt. No
podemos esquecer de fechar o arquivo:
>>> f.close()
Existem vrias maneiras de ler o que est escrito, a basica read()
>>> f = open('/home/igor/Python/texto', 'r')
>>> ler = f.read()
>>> f.close()
>>> print ler
Ola Mundo!
O metodo read() usado sem nenhum argumento, mostrar tudo que
esta no aquivo, mas se quisermos ler apenas os tres primeiros
caracters (bytes), podemos usar da seguinte maneira:
>>> f = open('/home/igor/Python/texto') #lembrando que o modo 'r'
pode ser excluido pois e o padrao
>>> ler = f.read(3)
>>> print ler
Ola

Aqui apenas especificamos que so sero lidos os tres primeiros


caracters (bytes), e caso queira ler o restante, o read() comear de
onde parou
>>> restante = f.read()
>>> print restante
Mundo!
Agora vamos adicionar mais alguma coisa no nosso arquivo:
>>> f = open('/home/igor/Python/texto','a')
>>> f.write('\nOla Python')
>>> f.close()
Aqui usamos o 'a' (append), pra adicionar sem apagar o que ja havia
no arquivo, e o '\n' usado pra pular uma linha, lembrando que tudo
string. Agora vamos ver o resultado de outras maneiras:
>>> f = file('/home/igor/Python/texto', 'r')
>>> linha1 = f.readline()
>>> linha2 = f.readline()
>>> f.close()
>>> print linha1
Ola Mundo!
>>> print linha2
Ola Python
O readline() sem argumento, ira ler todo o conteudo de uma linha,
porem possivel dar um limite de caracters, assim como o read.
linha1 guarda o conteudo da primeira linha, quando eu chamamos o
readline() mais uma vez, ele vai comear a ler de onde tinha parado,
ou seja, na segunda linha. Caso no tenha percebido, ao inves de
open, usamos file, que da o mesmo resultado.
Pra quem f de lista (como eu), no poderia faltar um metodo que
retornasse todo o conteudo do arquivo numa lista, e como tudo em

Python, ele ja est pronto! o readlines():


>>> f = open('/home/igor/Python/texto', 'r')
>>> ler = f.readlines()
>>> f.close()
>>> print ler
['Ola Mundo!\n', 'Ola Python']
Cada linha fica em um indice da lista, no formato de uma string.
Para verificar se o arquivo foi realmente fechado, basta digitar:
>>> f.closed
True

Reading and Writing Files in Python


<a href='http://ads.egrappler.com/www/delivery/ck.php?
n=af1b78cc&amp;cb=INSERT_RANDOM_NUMBER_HERE' target='_blank'><img
src='http://ads.egrappler.com/www/delivery/avw.php?
zoneid=77&amp;cb=INSERT_RANDOM_NUMBER_HERE&amp;n=af1b78cc' border='0'
alt='' /></a>

Overview
In Python, you don't need to import any library to read and write files.

The first step is to get a file object.

The way to do this is to use the open function.

File Types
A file is usually categorized as either text or binary.

A text file is often structured as a sequence of lines and a line is a sequence


of characters.

The line is terminated by a EOL (End Of Line) character.

The most common line terminator is the \n , or the newline character.

The backslash character indicates that the next character will be treated as a
newline.

A binary file is basically any file that is not a text file. Binary files can
only be processed by application that know about the file's structure.

Open ( )
To open a file for writing use the built-i open() function. open() returns a
file object, and is most commonly used with two arguments.

The syntax is:


file_object = open(filename, mode) where file_object is the variable to put the
file object.

The second argument describes the way in which the file will be used.

Mode
The mode argument is optional; 'r' will be assumed if its omitted.

The modes can be:

'r' when the file will only be read

'w' for only writing (an existing file with the same name will be erased)

'a' opens the file for appending; any data written to the file is automatically
added to the end.

'r+' opens the file for both reading and writing.


>>> f = open('workfile', 'w')
>>> print f
Next the file objects functions can be called. The two most common functions are
read and write.

Create a text file


Let's first create a new text file. You can name it anything you like,
in this example we will name it "newfile.txt".
file = open("newfile.txt", "w")

file.write("hello world in the new file\n")

file.write("and another line\n")

file.close()
If we now look in the newfile.txt, we can see the text that we wrote:
$ cat newfile.txt
hello world in the new file
and another line

How to read a text file


To read a file, we can use different methods.

file.read( )
If you want to return a string containing all characters in the file, you can
use file.read().
file = open('newfile.txt', 'r')

print file.read()
Output:

hello world in the new file


and another line
We can also specify how many characters the string should return, by using
file.read(n), where "n" determines number of characters.

This reads the first 5 characters of data and returns it as a string.


file = open('newfile.txt', 'r')
print file.read(5)
Output:

hello

file.readline( )
The readline() function will read from a file line by line (rather than pulling
the entire file in at once).

Use readline() when you want to get the first line of the file, subsequent calls
to readline() will return successive lines.

Basically, it will read a single line from the file and return a string
containing characters up to \n.
file = open('newfile.txt', 'r')

print file.readline():
Output:

hello world in the new file

file.readlines( )
readlines() returns the complete ?le as a list of strings each separated by \n
file = open('newfile.txt', 'r')

print file.readlines()
Output:

['hello world in the new file\n', 'and another line\n']

Looping over a file object


For reading lines from a file, you can loop over the file object.

This is memory efficient, fast, and leads to simple code.


file = open('newfile.txt', 'r')

for line in file:


print line,
Output:

hello world in the new file


and another line

file.write( )
The write method takes one parameter, which is the string to be written.

To start a new line after writing the data, add a \n character to the end.
file = open("newfile.txt", "w")

file.write("This is a test\n")

file.write("And here is another line\n")

file.close()

Close ( )
When youre done with a file, call f.close() to close it and free up any system
resources taken up by the open file.

After calling f.close(), attempts to use the file object will automatically fail.

File Handling Usages


Let's show some example on how to use the different file methods
To open a text file, use:
fh = open("hello.txt", "r")

To read a text file, use:


fh = open("hello.txt","r")
print fh.read()

To read one line at a time, use:


fh = open("hello".txt", "r")
print fh.readline()

To read a list of lines use:


fh = open("hello.txt.", "r")
print fh.readlines()

To write to a file, use:


fh = open("hello.txt","w")
fh.write("Hello World")

fh.close()

To write to a file, use:


fh = open("hello.txt", "w")
lines_of_text = ["a line of text", "another line of text", "a third line"]
fh.writelines(lines_of_text)
fh.close()

To append to file, use:


fh = open("Hello.txt", "a")
fh.write("Hello World again")
fh.close

To close a file, use


fh = open("hello.txt", "r")
print fh.read()
fh.close()

With Statement
Another way of working with file objects is the With statement.

It is good practice to use this statement.

With the "With" statement, you get better syntax and exceptions handling.
In addition, it will automatically close the file. The with statement provides a
way for ensuring that a clean-up is always used.
Opening a file using with is as simple as:
with open(filename) as file:

Let's take a look at some examples


with open("newtext.txt") as file:

# Use file to refer to the file object

data = file.read()
do something with data

You can of course also loop over the file object:


with open("newfile.txt") as f:
for line in f:

print line,
Notice, that we didn't have to write "file.close()". That will automatically be
called.

With Examples
Let's show some examples on how we can use this in our every day programming.

Write to a file using With


Write to a file using the With statement
with open("hello.txt", "w") as f:
f.write("Hello World")

Read a file line by line into an list


This will read the file hello.txt and save the content into "data".
with open(hello.txt) as f:
data = f.readlines()

Splitting Lines
As a last example, we will show how to split lines from a text file.

The split function in our example, splits the string contained in the variable
data, whenever it sees a space character.

You can split by whatever you wish, line.split(":") would split the line using
colons.
with open('data.txt', 'r') as f:
data = f.readlines()

for line in data:


words = line.split()
print words
Output:

Because multiple values are returned by split, they are returned as an array.
['hello', 'world,', 'how', 'are', 'you', 'today?']
['today', 'is', 'saturday']

Vous aimerez peut-être aussi