Python Write to File: explicación de las funciones de abrir, leer, adjuntar y otras funciones de manejo de archivos

Bienvenidos

¡Hola! Si desea aprender a trabajar con archivos en Python, este artículo es para usted. Trabajar con archivos es una habilidad importante que todo desarrollador de Python debería aprender, así que comencemos.

En este artículo, aprenderá:

  • Cómo abrir un archivo.
  • Cómo leer un archivo.
  • Cómo crear un archivo.
  • Cómo modificar un archivo.
  • Cómo cerrar un archivo.
  • Cómo abrir archivos para múltiples operaciones.
  • Cómo trabajar con métodos de objeto de archivo.
  • Cómo borrar archivos.
  • Cómo trabajar con administradores de contexto y por qué son útiles.
  • Cómo manejar las excepciones que podrían surgir al trabajar con archivos.
  • ¡y más!

¡Vamos a empezar! ✨

? Trabajar con archivos: sintaxis básica

Una de las funciones más importantes que usted tendrá que utilizar a medida que trabaja con archivos en Python es open(), una función incorporada que se abre un archivo y permite que su programa para usarlo y trabajar con él.

Esta es la sintaxis básica :

? Sugerencia: Estos son los dos argumentos más utilizados para llamar a esta función. Hay seis argumentos opcionales adicionales. Para obtener más información sobre ellos, lea este artículo en la documentación.

Primer parámetro: archivo

El primer parámetro de la open()función es filela ruta absoluta o relativa al archivo con el que está intentando trabajar.

Por lo general, usamos una ruta relativa, que indica dónde se encuentra el archivo en relación con la ubicación del script (archivo Python) que llama a la open()función.

Por ejemplo, la ruta en esta llamada de función:

open("names.txt") # The relative path is "names.txt"

Solo contiene el nombre del archivo. Esto se puede usar cuando el archivo que está intentando abrir está en el mismo directorio o carpeta que el script de Python, así:

Pero si el archivo está dentro de una carpeta anidada, así:

Luego, necesitamos usar una ruta específica para decirle a la función que el archivo está dentro de otra carpeta.

En este ejemplo, esta sería la ruta:

open("data/names.txt")

Observe que estamos escribiendo data/primero (el nombre de la carpeta seguido de a /) y luego names.txt(el nombre del archivo con la extensión).

? Sugerencia: Las tres letras .txtque siguen al punto names.txtson la "extensión" del archivo o su tipo. En este caso, .txtindica que es un archivo de texto.

Segundo parámetro: modo

El segundo parámetro de la open()función es mode, una cadena con un carácter. Ese único carácter básicamente le dice a Python lo que planea hacer con el archivo en su programa.

Los modos disponibles son:

  • Leer ( "r").
  • Agregar ( "a")
  • Escribir ( "w")
  • Crear ( "x")

También puede optar por abrir el archivo en:

  • Modo de texto ( "t")
  • Modo binario ( "b")

Para usar el modo texto o binario, necesitaría agregar estos caracteres al modo principal. Por ejemplo: "wb"significa escribir en modo binario.

? Sugerencia: Los modos predeterminados son lectura ( "r") y texto ( "t"), que significa "abierto para leer texto" ( "rt"), por lo que no es necesario especificarlos open()si desea usarlos porque están asignados de manera predeterminada. Simplemente puede escribir open().

¿Por qué modos?

Realmente tiene sentido que Python otorgue solo ciertos permisos en función de lo que planea hacer con el archivo, ¿verdad? ¿Por qué Python debería permitir que su programa haga más de lo necesario? Básicamente, esta es la razón por la que existen los modos.

Piénselo: permitir que un programa haga más de lo necesario puede resultar problemático. Por ejemplo, si sólo necesita leer el contenido de un archivo, puede ser peligroso permitir que su programa lo modifique inesperadamente, lo que podría introducir errores.

? Cómo leer un archivo

Ahora que sabe más sobre los argumentos que open()toma la función, veamos cómo puede abrir un archivo y almacenarlo en una variable para usarlo en su programa.

Esta es la sintaxis básica:

Simplemente estamos asignando el valor devuelto a una variable. Por ejemplo:

names_file = open("data/names.txt", "r")

Sé que podría estar preguntando: ¿qué tipo de valor devuelve open()?

Bueno, un objeto de archivo .

Hablemos un poco de ellos.

Objetos de archivo

Según la documentación de Python, un objeto de archivo es:

Un objeto que expone una API orientada a archivos (con métodos como read () o write ()) a un recurso subyacente.

Básicamente, esto nos dice que un objeto de archivo es un objeto que nos permite trabajar e interactuar con archivos existentes en nuestro programa Python.

Los objetos de archivo tienen atributos, como:

  • name: the name of the file.
  • closed: True if the file is closed. False otherwise.
  • mode: the mode used to open the file.

For example:

f = open("data/names.txt", "a") print(f.mode) # Output: "a"

Now let's see how you can access the content of a file through a file object.

Methods to Read a File

For us to be able to work file objects, we need to have a way to "interact" with them in our program and that is exactly what methods do. Let's see some of them.

Read()

The first method that you need to learn about is read(),which returns the entire content of the file as a string.

Here we have an example:

f = open("data/names.txt") print(f.read())

The output is:

Nora Gino Timmy William

You can use the type() function to confirm that the value returned by f.read() is a string:

print(type(f.read())) # Output 

Yes, it's a string!

In this case, the entire file was printed because we did not specify a maximum number of bytes, but we can do this as well.

Here we have an example:

f = open("data/names.txt") print(f.read(3))

The value returned is limited to this number of bytes:

Nor

❗️Important: You need to close a file after the task has been completed to free the resources associated to the file. To do this, you need to call the close() method, like this:

Readline() vs. Readlines()

You can read a file line by line with these two methods. They are slightly different, so let's see them in detail.

readline() reads one line of the file until it reaches the end of that line. A trailing newline character (\n) is kept in the string.

? Tip: Optionally, you can pass the size, the maximum number of characters that you want to include in the resulting string.

For example:

f = open("data/names.txt") print(f.readline()) f.close()

The output is:

Nora 

This is the first line of the file.

In contrast, readlines() returns a list with all the lines of the file as individual elements (strings). This is the syntax:

For example:

f = open("data/names.txt") print(f.readlines()) f.close()

The output is:

['Nora\n', 'Gino\n', 'Timmy\n', 'William']

Notice that there is a \n (newline character) at the end of each string, except the last one.

? Tip: You can get the same list with list(f).

You can work with this list in your program by assigning it to a variable or using it in a loop:

f = open("data/names.txt") for line in f.readlines(): # Do something with each line f.close()

We can also iterate over f directly (the file object) in a loop:

f = open("data/names.txt", "r") for line in f: # Do something with each line f.close()

Those are the main methods used to read file objects. Now let's see how you can create files.

? Cómo crear un archivo

Si necesita crear un archivo "dinámicamente" usando Python, puede hacerlo con el "x"modo.

Veamos cómo. Esta es la sintaxis básica:

He aquí un ejemplo. Este es mi directorio de trabajo actual:

Si ejecuto esta línea de código:

f = open("new_file.txt", "x")

Se crea un nuevo archivo con ese nombre:

Con este modo, puede crear un archivo y luego escribir en él dinámicamente usando métodos que aprenderá en solo unos momentos.

? Sugerencia: El archivo estará inicialmente vacío hasta que lo modifique.

Una cosa curiosa es que si intentas ejecutar esta línea nuevamente y ya existe un archivo con ese nombre, verás este error:

Traceback (most recent call last): File "", line 8, in  f = open("new_file.txt", "x") FileExistsError: [Errno 17] File exists: 'new_file.txt'

Según la documentación de Python, esta excepción (error de tiempo de ejecución) es:

Se genera al intentar crear un archivo o directorio que ya existe.

Now that you know how to create a file, let's see how you can modify it.

? How to Modify a File

To modify (write to) a file, you need to use the write() method. You have two ways to do it (append or write) based on the mode that you choose to open it with. Let's see them in detail.

Append

"Appending" means adding something to the end of another thing. The "a" mode allows you to open a file to append some content to it.

For example, if we have this file:

And we want to add a new line to it, we can open it using the "a" mode (append) and then, call the write() method, passing the content that we want to append as argument.

This is the basic syntax to call the write()method:

Here's an example:

f = open("data/names.txt", "a") f.write("\nNew Line") f.close()

? Tip: Notice that I'm adding \n before the line to indicate that I want the new line to appear as a separate line, not as a continuation of the existing line.

This is the file now, after running the script:

? Tip: The new line might not be displayed in the file untilf.close() runs.

Write

Sometimes, you may want to delete the content of a file and replace it entirely with new content. You can do this with the write() method if you open the file with the "w" mode.

Here we have this text file:

If I run this script:

f = open("data/names.txt", "w") f.write("New Content") f.close() 

This is the result:

As you can see, opening a file with the "w" mode and then writing to it replaces the existing content.

? Tip: The write() method returns the number of characters written.

If you want to write several lines at once, you can use the writelines() method, which takes a list of strings. Each string represents a line to be added to the file.

Here's an example. This is the initial file:

If we run this script:

f = open("data/names.txt", "a") f.writelines(["\nline1", "\nline2", "\nline3"]) f.close()

The lines are added to the end of the file:

Open File For Multiple Operations

Now you know how to create, read, and write to a file, but what if you want to do more than one thing in the same program? Let's see what happens if we try to do this with the modes that you have learned so far:

If you open a file in "r" mode (read), and then try to write to it:

f = open("data/names.txt") f.write("New Content") # Trying to write f.close()

You will get this error:

Traceback (most recent call last): File "", line 9, in  f.write("New Content") io.UnsupportedOperation: not writable

Similarly, if you open a file in "w" mode (write), and then try to read it:

f = open("data/names.txt", "w") print(f.readlines()) # Trying to read f.write("New Content") f.close()

You will see this error:

Traceback (most recent call last): File "", line 14, in  print(f.readlines()) io.UnsupportedOperation: not readable

The same will occur with the "a" (append) mode.

How can we solve this? To be able to read a file and perform another operation in the same program, you need to add the "+" symbol to the mode, like this:

f = open("data/names.txt", "w+") # Read + Write
f = open("data/names.txt", "a+") # Read + Append
f = open("data/names.txt", "r+") # Read + Write

Very useful, right? This is probably what you will use in your programs, but be sure to include only the modes that you need to avoid potential bugs.

Sometimes files are no longer needed. Let's see how you can delete files using Python.

? How to Delete Files

To remove a file using Python, you need to import a module called os which contains functions that interact with your operating system.

? Tip: A module is a Python file with related variables, functions, and classes.

Particularly, you need the remove()function. This function takes the path to the file as argument and deletes the file automatically.

Let's see an example. We want to remove the file called sample_file.txt.

To do it, we write this code:

import os os.remove("sample_file.txt")
  • The first line: import os is called an "import statement". This statement is written at the top of your file and it gives you access to the functions defined in the os module.
  • The second line: os.remove("sample_file.txt") removes the file specified.

? Tip: you can use an absolute or a relative path.

Now that you know how to delete files, let's see an interesting tool... Context Managers!

? Meet Context Managers

Context Managers are Python constructs that will make your life much easier. By using them, you don't need to remember to close a file at the end of your program and you have access to the file in the particular part of the program that you choose.

Syntax

This is an example of a context manager used to work with files:

? Tip: The body of the context manager has to be indented, just like we indent loops, functions, and classes. If the code is not indented, it will not be considered part of the context manager.

When the body of the context manager has been completed, the file closes automatically.

with open("", "") as : # Working with the file... # The file is closed here!

Example

Here's an example:

with open("data/names.txt", "r+") as f: print(f.readlines()) 

This context manager opens the names.txt file for read/write operations and assigns that file object to the variable f. This variable is used in the body of the context manager to refer to the file object.

Trying to Read it Again

After the body has been completed, the file is automatically closed, so it can't be read without opening it again. But wait! We have a line that tries to read it again, right here below:

with open("data/names.txt", "r+") as f: print(f.readlines()) print(f.readlines()) # Trying to read the file again, outside of the context manager

Veamos qué pasa:

Traceback (most recent call last): File "", line 21, in  print(f.readlines()) ValueError: I/O operation on closed file.

Este error se produce porque estamos intentando leer un archivo cerrado. Impresionante, ¿verdad? El administrador de contexto hace todo el trabajo pesado por nosotros, es legible y conciso.

? Cómo manejar excepciones al trabajar con archivos

Cuando trabaja con archivos, pueden producirse errores. A veces, es posible que no tenga los permisos necesarios para modificar o acceder a un archivo, o es posible que un archivo ni siquiera exista.

Como programador, debe prever estas circunstancias y manejarlas en su programa para evitar bloqueos repentinos que definitivamente podrían afectar la experiencia del usuario.

Veamos algunas de las excepciones más comunes (errores de tiempo de ejecución) que puede encontrar cuando trabaja con archivos:

FileNotFoundError

Según la documentación de Python, esta excepción es:

Se genera cuando se solicita un archivo o directorio, pero no existe.

For example, if the file that you're trying to open doesn't exist in your current working directory:

f = open("names.txt")

You will see this error:

Traceback (most recent call last): File "", line 8, in  f = open("names.txt") FileNotFoundError: [Errno 2] No such file or directory: 'names.txt'

Let's break this error down this line by line:

  • File "", line 8, in . This line tells you that the error was raised when the code on the file located in was running. Specifically, when line 8 was executed in .
  • f = open("names.txt"). This is the line that caused the error.
  • FileNotFoundError: [Errno 2] No such file or directory: 'names.txt' . This line says that a FileNotFoundError exception was raised because the file or directory names.txt doesn't exist.

? Tip: Python is very descriptive with the error messages, right? This is a huge advantage during the process of debugging.

PermissionError

This is another common exception when working with files. According to the Python Documentation, this exception is:

Se genera cuando se intenta ejecutar una operación sin los derechos de acceso adecuados, por ejemplo, los permisos del sistema de archivos.

Esta excepción se genera cuando intenta leer o modificar un archivo que no tiene permiso de acceso. Si intenta hacerlo, verá este error:

Traceback (most recent call last): File "", line 8, in  f = open("") PermissionError: [Errno 13] Permission denied: 'data'

IsADirectoryError

Según la documentación de Python, esta excepción es:

Se genera cuando se solicita una operación de archivo en un directorio.

Esta excepción en particular se genera cuando intenta abrir o trabajar en un directorio en lugar de un archivo, así que tenga mucho cuidado con la ruta que pasa como argumento.

Cómo manejar las excepciones

Para manejar estas excepciones, puede usar una declaración try / except . Con esta declaración, puede "decirle" a su programa qué hacer en caso de que ocurra algo inesperado.

Esta es la sintaxis básica:

try: # Try to run this code except : # If an exception of this type is raised, stop the process and jump to this block 

Here you can see an example with FileNotFoundError:

try: f = open("names.txt") except FileNotFoundError: print("The file doesn't exist")

This basically says:

  • Try to open the file names.txt.
  • If a FileNotFoundError is thrown, don't crash! Simply print a descriptive statement for the user.

? Tip: You can choose how to handle the situation by writing the appropriate code in the except block. Perhaps you could create a new file if it doesn't exist already.

To close the file automatically after the task (regardless of whether an exception was raised or not in the try block) you can add the finally block.

try: # Try to run this code except : # If this exception is raised, stop the process immediately and jump to this block finally: # Do this after running the code, even if an exception was raised

This is an example:

try: f = open("names.txt") except FileNotFoundError: print("The file doesn't exist") finally: f.close()

There are many ways to customize the try/except/finally statement and you can even add an else block to run a block of code only if no exceptions were raised in the try block.

? Tip: To learn more about exception handling in Python, you may like to read my article: "How to Handle Exceptions in Python: A Detailed Visual Introduction".

? In Summary

  • You can create, read, write, and delete files using Python.
  • File objects have their own set of methods that you can use to work with them in your program.
  • Context Managers help you work with files and manage them by closing them automatically when a task has been completed.
  • Exception handling is key in Python. Common exceptions when you are working with files include FileNotFoundError, PermissionError and IsADirectoryError. They can be handled using try/except/else/finally.

I really hope you liked my article and found it helpful. Now you can work with files in your Python projects. Check out my online courses. Follow me on Twitter. ⭐️