Na função python built-in open, qual é a diferença exata entre os modos w
, a
, w+
, a+
, e r+
?
Em particular, a documentação implica que todos eles permitirão escrever no arquivo, e diz que ele abre os arquivos para "appending", "writing" e "updating" especificamente, mas não define o que estes termos significam.
Os modos de abertura são exatamente os mesmos da função de biblioteca padrão C **fopen()
***.
O BSD fopen
manpage]1 define-os da seguinte forma:
The argument mode points to a string beginning with one of the following
sequences (Additional characters may follow these sequences.):
``r'' Open text file for reading. The stream is positioned at the
beginning of the file.
``r+'' Open for reading and writing. The stream is positioned at the
beginning of the file.
``w'' Truncate file to zero length or create text file for writing.
The stream is positioned at the beginning of the file.
``w+'' Open for reading and writing. The file is created if it does not
exist, otherwise it is truncated. The stream is positioned at
the beginning of the file.
``a'' Open for writing. The file is created if it does not exist. The
stream is positioned at the end of the file. Subsequent writes
to the file will always end up at the then current end of file,
irrespective of any intervening fseek(3) or similar.
``a+'' Open for reading and writing. The file is created if it does not
exist. The stream is positioned at the end of the file. Subse-
quent writes to the file will always end up at the then current
end of file, irrespective of any intervening fseek(3) or similar.
As opções são as mesmas que para o fopen function na biblioteca padrão C:
"w" truncata o arquivo, sobrescrevendo o que já estava lá
`a' anexa ao arquivo, adicionando ao que já estava lá
O w+
abre para leitura e escrita, truncando o arquivo, mas também permitindo que você leia de volta o que's foi escrito no arquivo
a+" abre para anexar e ler, permitindo-lhe anexar ao ficheiro e também ler o seu conteúdo
Tento descobrir porque usaria o modo 'w+' versus 'w'. No final, eu só fiz alguns testes. Não vejo muito propósito para o modo 'w+' como em ambos os casos, o arquivo é truncado para começar. Entretanto, com o 'w+', você poderia ler depois de escrever, procurando de volta. Se você tentou qualquer leitura com 'w', isso levantaria um IOError. Ler sem usar a busca com o modo 'w+' não vai render nada, já que o ponteiro do arquivo será depois de onde você escreveu.