Practicando con los Modos de Lectura/Escritura y Eligiendo el Modo Correcto
Python también proporciona modos que permiten tanto la lectura como la escritura dentro del mismo contexto open()
. Estos ofrecen más flexibilidad, pero requieren un manejo cuidadoso del puntero del archivo.
- Lectura y Escritura (
'r+'
): Abre un archivo existente para lectura y escritura. El puntero comienza al principio. La escritura sobrescribirá el contenido existente desde la posición del puntero.
- Escritura y Lectura (
'w+'
): Abre un archivo para escritura y lectura. Trunca el archivo si existe o lo crea si no. El puntero comienza al principio.
- Añadir y Lectura (
'a+'
): Abre un archivo para añadir (escribir al final) y leer. Crea el archivo si no existe. El puntero comienza al final para escribir, pero puede moverlo (por ejemplo, usando file.seek(0)
) para leer desde el principio.
Demostremos 'r+'
. Usaremos el archivo my_reading_file.txt
creado en el Paso 1. Lo abriremos, leeremos el contenido, luego moveremos el puntero al principio y sobrescribiremos el comienzo del archivo.
Cree un archivo de Python llamado rplus_example.py
en /home/labex/project
. Agregue este código:
try:
## Open the file in read and write mode ('r+')
## The file must exist for this mode.
with open('/home/labex/project/my_reading_file.txt', 'r+') as file:
## Read the initial content
initial_content = file.read()
print("Initial file content:")
print(initial_content)
## Move the file pointer back to the beginning
print("\nMoving pointer to the beginning using file.seek(0).")
file.seek(0)
## Write new content at the beginning (overwriting existing content)
print("Writing new content...")
file.write("Prepended line 1.\n")
file.write("Prepended line 2.\n")
## If the new content is shorter than what was overwritten,
## the rest of the original content might remain unless truncated.
## We can use file.truncate() after writing to remove any trailing old data.
print("Truncating file to the current position to remove old trailing data.")
file.truncate()
print("\nContent written and file truncated.")
except FileNotFoundError:
print("Error: The file was not found. 'r+' requires the file to exist.")
except Exception as e:
print(f"An error occurred: {e}")
print("\nFinished with r+ mode example.")
Este script abre el archivo en 'r+'
, lee, busca (seeks) de nuevo al principio (file.seek(0)
), escribe nuevas líneas (sobrescribiendo) y luego usa file.truncate()
para eliminar cualquier contenido original restante que pueda existir más allá del texto recién escrito.
Guarde rplus_example.py
. Antes de ejecutarlo, asegurémonos de que my_reading_file.txt
tenga su contenido original:
echo "This is the first line." > /home/labex/project/my_reading_file.txt
echo "This is the second line." >> /home/labex/project/my_reading_file.txt
Ahora, ejecute el script de Python desde la terminal:
python rplus_example.py
Verá el contenido inicial impreso, seguido de mensajes sobre el proceso:
Initial file content:
This is the first line.
This is the second line.
Moving pointer to the beginning using file.seek(0).
Writing new content...
Truncating file to the current position to remove old trailing data.
Content written and file truncated.
Finished with r+ mode example.
Verifique el contenido final del archivo usando cat
:
cat /home/labex/project/my_reading_file.txt
La salida debería mostrar solo el contenido recién escrito, gracias a la sobrescritura y al truncamiento:
Prepended line 1.
Prepended line 2.
Eligiendo el Modo de Acceso a Archivos Apropiado
Seleccionar el modo correcto es vital. Aquí hay una guía rápida:
- Use
'r'
para acceso de solo lectura a archivos existentes.
- Use
'w'
para crear un nuevo archivo o reemplazar completamente el contenido de un archivo existente.
- Use
'a'
para agregar al final de un archivo sin perder los datos existentes (bueno para registros/logs).
- Use
'r+'
para leer y modificar un archivo existente desde el principio.
- Use
'w+'
para crear o sobrescribir un archivo y luego leerlo/escribirlo.
- Use
'a+'
para añadir a un archivo y también poder leerlo (requiere usar seek()
).
Esta tabla resume los comportamientos clave:
Modo |
Leer (Read) |
Escribir (Write) |
Crear si no existe (Create if not exists) |
Truncar si existe (Truncate if exists) |
Posición del Puntero (Inicial) (Pointer Position (Initial)) |
'r' |
Sí (Yes) |
No |
No |
No |
Comienzo (Beginning) |
'w' |
No |
Sí (Yes) |
Sí (Yes) |
Sí (Yes) |
Comienzo (Beginning) |
'a' |
No |
Sí (Yes) |
Sí (Yes) |
No |
Final (End) |
'r+' |
Sí (Yes) |
Sí (Yes) |
No |
No |
Comienzo (Beginning) |
'w+' |
Sí (Yes) |
Sí (Yes) |
Sí (Yes) |
Sí (Yes) |
Comienzo (Beginning) |
'a+' |
Sí (Yes) |
Sí (Yes) |
Sí (Yes) |
No |
Final (End) |
Al considerar si necesita leer, escribir, añadir, manejar archivos existentes o crear nuevos, puede elegir con confianza el modo más adecuado para su tarea.