En la función incorporada de python open, ¿cuál es la diferencia exacta entre los modos w
, a
, w+
, a+
y r+
?
En particular, la documentación implica que todos ellos permitirán escribir en el archivo, y dice que abre los archivos para "añadir", "escribir", y "actualizar" específicamente, pero no define qué significan estos términos.
Los modos de apertura son exactamente los mismos que los de la función de la biblioteca estándar de C fopen()
.
La página de manual de BSD fopen
los define como sigue:
lenguaje: ninguno -->
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.
Las opciones son las mismas que para la función fopen de la biblioteca estándar de C:
w
trunca el archivo, sobrescribiendo lo que ya estaba allí
a
agrega al archivo, añadiendo lo que ya existía
w+
abre para leer y escribir, truncando el archivo pero también permitiendo leer lo que se ha escrito en él
a+
se abre para añadir y leer, permitiendo tanto añadir al archivo como leer su contenido
Me encontré con esto tratando de averiguar por qué se utiliza el modo 'w+' frente a 'w'. Al final, sólo hice algunas pruebas. No veo mucho propósito para el modo 'w+', ya que en ambos casos, el archivo se trunca para empezar. Sin embargo, con el 'w+', podrías leer después de escribir buscando hacia atrás. Si intentara cualquier lectura con 'w', se produciría un IOError. La lectura sin usar la búsqueda con el modo 'w+' no va a producir nada, ya que el puntero del archivo estará después de donde haya escrito.