¿Cuáles son las diferencias entre los modos de acceso a archivos en Python?

PythonPythonBeginner
Practicar Ahora

💡 Este tutorial está traducido por IA desde la versión en inglés. Para ver la versión original, puedes hacer clic aquí

Introducción

Las capacidades de manejo de archivos de Python son esenciales para una amplia gama de aplicaciones. Comprender los diferentes modos de acceso a archivos es crucial para gestionar y manipular archivos de forma eficaz. Este laboratorio profundizará en los modos de acceso a archivos comunes en Python, sus diferencias y cómo seleccionar el modo apropiado para su caso de uso específico.

En este laboratorio, aprenderá sobre los modos de acceso a archivos fundamentales en Python, explorará sus casos de uso comunes y comprenderá cómo elegir el modo apropiado para sus operaciones de archivo.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/ErrorandExceptionHandlingGroup(["Error and Exception Handling"]) python(("Python")) -.-> python/FileHandlingGroup(["File Handling"]) python/ErrorandExceptionHandlingGroup -.-> python/catching_exceptions("Catching Exceptions") python/FileHandlingGroup -.-> python/file_opening_closing("Opening and Closing Files") python/FileHandlingGroup -.-> python/file_reading_writing("Reading and Writing Files") python/FileHandlingGroup -.-> python/file_operations("File Operations") subgraph Lab Skills python/catching_exceptions -.-> lab-397713{{"¿Cuáles son las diferencias entre los modos de acceso a archivos en Python?"}} python/file_opening_closing -.-> lab-397713{{"¿Cuáles son las diferencias entre los modos de acceso a archivos en Python?"}} python/file_reading_writing -.-> lab-397713{{"¿Cuáles son las diferencias entre los modos de acceso a archivos en Python?"}} python/file_operations -.-> lab-397713{{"¿Cuáles son las diferencias entre los modos de acceso a archivos en Python?"}} end

Entendiendo y Practicando el Modo Lectura ('r')

En Python, los modos de acceso a archivos especifican cómo se debe abrir un archivo y qué operaciones (como lectura o escritura) están permitidas. Comprender estos modos es crucial para un manejo eficaz de archivos. Al usar la función incorporada open(), se proporciona la ruta del archivo y, opcionalmente, una cadena de modo (mode string). Por ejemplo, open('my_file.txt', 'r') abre el archivo para lectura.

Aquí hay una descripción general rápida de los modos comunes:

  • Modo Lectura ('r'): Se abre para lectura (predeterminado). Puntero al principio. Lanza FileNotFoundError si el archivo no existe.
  • Modo Escritura ('w'): Se abre para escritura. Trunca (borra) el archivo si existe, lo crea si no. Puntero al principio.
  • Modo Añadir ('a'): Se abre para escritura. Puntero al final si el archivo existe, lo crea si no. Los nuevos datos se agregan al final.
  • Lectura y Escritura ('r+'): Abre un archivo existente para lectura y escritura. Puntero al principio.
  • Escritura y Lectura ('w+'): Se abre para escritura y lectura. Trunca o crea el archivo. Puntero al principio.
  • Añadir y Lectura ('a+'): Se abre para añadir y lectura. Puntero al final para escribir. Crea el archivo si no existe.

Practiquemos con el modo más básico: lectura ('r'). Este modo se utiliza puramente para leer el contenido de un archivo existente. El puntero del archivo comienza al principio. Recuerde, intentar abrir un archivo inexistente en modo 'r' causará un error.

Primero, necesitamos un archivo para leer. Usando el editor VS Code dentro de LabEx, navegue al directorio /home/labex/project en el explorador de archivos. Cree un nuevo archivo llamado my_reading_file.txt. Agregue las siguientes líneas y guarde el archivo:

This is the first line.
This is the second line.

Ahora, cree un script de Python en el mismo directorio llamado read_example.py. Agregue el siguiente código, que abre el archivo de texto en modo lectura, lee su contenido y lo imprime. Incluimos un bloque try...except para manejar con elegancia el caso en que el archivo no se encuentre.

try:
    ## Open the file in read mode ('r')
    with open('/home/labex/project/my_reading_file.txt', 'r') as file:
        ## Read the entire content of the file
        content = file.read()
        print("File content:")
        print(content)
except FileNotFoundError:
    print("Error: The file my_reading_file.txt was not found.")
except Exception as e:
    print(f"An error occurred: {e}")

print("\\nFinished reading the file.")

Guarde este script de Python. Luego, abra la terminal en VS Code (Terminal > New Terminal). Asegúrese de estar en el directorio correcto ejecutando pwd, que debería mostrar /home/labex/project.

Ejecute el script usando el intérprete de Python:

python read_example.py

Debería ver el contenido de my_reading_file.txt impreso en la terminal, seguido del mensaje de finalización:

File content:
This is the first line.
This is the second line.

Finished reading the file.

Esto demuestra la apertura y lectura exitosa de un archivo usando el modo 'r'.

Illustration of reading a file

Practicando con el Modo Escritura ('w')

El modo escritura ('w') se utiliza cuando se desea escribir en un archivo. Tenga cuidado: si el archivo ya existe, abrirlo en modo 'w' lo truncará, lo que significa que todo su contenido anterior se borrará. Si el archivo no existe, el modo 'w' lo creará por usted. Este modo es ideal para crear archivos nuevos o comenzar de nuevo con uno existente.

Intentemos escribir en un archivo. En su directorio /home/labex/project, cree un nuevo archivo de Python llamado write_example.py. Agregue el siguiente código. Este script abrirá (o creará) my_writing_file.txt en modo escritura y escribirá dos líneas en él.

try:
    ## Open the file in write mode ('w')
    ## If the file exists, its content will be overwritten.
    ## If the file does not exist, it will be created.
    with open('/home/labex/project/my_writing_file.txt', 'w') as file:
        ## Write some content to the file
        file.write("This is the first line written in write mode.\n")
        file.write("This is the second line.\n")
    print("Content successfully written to my_writing_file.txt")

except Exception as e:
    print(f"An error occurred: {e}")

print("\nFinished writing to the file.")

Guarde el script write_example.py. En la terminal (todavía en /home/labex/project), ejecute el script:

python write_example.py

Debería ver un mensaje de confirmación:

Content successfully written to my_writing_file.txt

Finished writing to the file.

Para confirmar que el archivo se creó y contiene el texto correcto, use el comando cat en la terminal:

cat /home/labex/project/my_writing_file.txt

La salida debería ser exactamente lo que escribió el script:

This is the first line written in write mode.
This is the second line.

Esto demuestra cómo crear o sobrescribir un archivo y escribir contenido en él usando el modo 'w'.

Practicando con el Modo Añadir ('a')

A diferencia del modo escritura ('w'), el modo añadir ('a') se utiliza para agregar contenido al final de un archivo existente sin eliminar su contenido actual. Si el archivo no existe, el modo 'a' lo creará. El puntero del archivo se coloca automáticamente al final del archivo cuando se abre, por lo que cualquier operación write() agregará datos.

Agreguemos algunas líneas al archivo my_writing_file.txt que creamos en el paso anterior. Cree un nuevo script de Python llamado append_example.py en /home/labex/project con el siguiente código:

try:
    ## Open the file in append mode ('a')
    ## If the file exists, new content will be added to the end.
    ## If the file does not exist, it will be created.
    with open('/home/labex/project/my_writing_file.txt', 'a') as file:
        ## Append some content to the file
        file.write("This line is appended.\n")
        file.write("Another line is appended.\n")
    print("Content successfully appended to my_writing_file.txt")

except Exception as e:
    print(f"An error occurred: {e}")

print("\nFinished appending to the file.")

Guarde este script. Ahora, ejecútelo desde la terminal:

python append_example.py

El script confirmará la operación de añadir:

Content successfully appended to my_writing_file.txt

Finished appending to the file.

Para ver el resultado, use cat nuevamente para ver todo el archivo:

cat /home/labex/project/my_writing_file.txt

Debería ver las dos líneas originales seguidas de las dos líneas recién agregadas:

This is the first line written in write mode.
This is the second line.
This line is appended.
Another line is appended.

El modo añadir es muy útil para tareas como agregar entradas de registro (log entries) o agregar nuevos registros a un archivo de datos sin perder los datos anteriores.

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.

Resumen

En este laboratorio, ha aprendido sobre los diversos modos de acceso a archivos en Python y sus diferencias clave. Exploró los modos 'r', 'w' y 'a' para operaciones básicas de lectura, escritura y adición (appending), respectivamente. También tocó brevemente los modos de lectura y escritura ('r+', 'w+', 'a+') que ofrecen más flexibilidad.

Al practicar con estos modos y comprender su comportamiento con respecto a la creación de archivos, el truncamiento y la posición del puntero, ahora está equipado para elegir el modo apropiado para sus tareas de manejo de archivos en Python. Este conocimiento es fundamental para administrar y manipular archivos de manera efectiva en sus aplicaciones.