Leitura e Escrita de Arquivos
Para um olhar mais aprofundado sobre a manipulação de caminhos de arquivos e diretórios, consulte a página Caminhos de Arquivos e Diretórios.
O processo de Leitura/Escrita de arquivos
Para ler/escrever em um arquivo em Python, você desejará usar a instrução with, que fechará o arquivo para você depois de terminar, gerenciando os recursos disponíveis.
Abrindo e lendo arquivos
A função open abre um arquivo e retorna um objeto de arquivo correspondente.
# Read file using 'with' statement: automatically closes file when done
with open('/home/labex/project/hi.txt') as hello_file:
hello_content = hello_file.read() # Read entire file content
hello_content
'Hello World!'
Quiz
Faça login para responder este quiz e acompanhar seu progresso de aprendizagem
What is the main advantage of using the
with statement when opening files?A. O arquivo é fechado automaticamente quando terminado, mesmo que ocorra um erro
B. Arquivos abrem mais rápido
C. Arquivos podem ser abertos em modo de leitura e escrita simultaneamente
D. Arquivos são automaticamente compactados
Alternativamente, você pode usar o método readlines() para obter uma lista de valores de string do arquivo, uma string para cada linha de texto:
# readlines() method: returns list of strings, one per line
with open('sonnet29.txt') as sonnet_file:
sonnet_file.readlines() # Returns list with each line as a string
['When, in disgrace with fortune and men's eyes,\n',
' I all alone beweep my outcast state,\n',
"And trouble deaf heaven with my bootless cries,\n",
"And look upon myself and curse my fate,']
Você também pode iterar sobre o arquivo linha por linha:
# Iterate through file line by line (memory efficient for large files)
with open('sonnet29.txt') as sonnet_file:
for line in sonnet_file: # File object is iterable
print(line, end='') # Print without extra newline
When, in disgrace with fortune and men's eyes,
I all alone beweep my outcast state,
And trouble deaf heaven with my bootless cries,
And look upon myself and curse my fate,
Escrevendo em arquivos
# Write to file: 'w' mode overwrites existing file
with open('bacon.txt', 'w') as bacon_file: # 'w' = write mode
bacon_file.write('Hello world!\n') # Returns number of characters written
13
# Append to file: 'a' mode appends to existing file
with open('bacon.txt', 'a') as bacon_file: # 'a' = append mode
bacon_file.write('Bacon is not a vegetable.')
25
with open('bacon.txt') as bacon_file:
content = bacon_file.read()
print(content)
Hello world!
Bacon is not a vegetable.
Quiz
Faça login para responder este quiz e acompanhar seu progresso de aprendizagem
What is the difference between opening a file with mode
'w' and mode 'a'?A.
'w' é para leitura, 'a' é para escritaB.
'w' sobrescreve o arquivo, 'a' anexa ao arquivoC.
'w' é para Windows, 'a' é para AppleD. Não há diferença