E / S de archivos de Python: lectura y escritura de archivos en Python

En este tutorial, aprenderá sobre las operaciones de archivos de Python. Más específicamente, abrir un archivo, leerlo, escribir en él, cerrarlo y varios métodos de archivo que debe conocer.

Video: lectura y escritura de archivos en Python

Archivos

Los archivos son ubicaciones con nombre en el disco para almacenar información relacionada. Se utilizan para almacenar datos de forma permanente en una memoria no volátil (por ejemplo, disco duro).

Dado que la memoria de acceso aleatorio (RAM) es volátil (que pierde sus datos cuando se apaga la computadora), usamos archivos para el uso futuro de los datos almacenándolos permanentemente.

Cuando queremos leer o escribir en un archivo, primero debemos abrirlo. Cuando hayamos terminado, es necesario cerrarlo para que se liberen los recursos que están vinculados con el archivo.

Por lo tanto, en Python, una operación de archivo se realiza en el siguiente orden:

  1. Abrir un archivo
  2. Leer o escribir (realizar operación)
  3. Cerrar el archivo

Abrir archivos en Python

Python tiene una open()función incorporada para abrir un archivo. Esta función devuelve un objeto de archivo, también llamado identificador, ya que se usa para leer o modificar el archivo en consecuencia.

 >>> f = open("test.txt") # open file in current directory >>> f = open("C:/Python38/README.txt") # specifying full path

Podemos especificar el modo al abrir un archivo. En modo, especificamos si queremos leer r, escribir wo agregar aal archivo. También podemos especificar si queremos abrir el archivo en modo texto o en modo binario.

El valor predeterminado es leer en modo texto. En este modo, obtenemos cadenas al leer del archivo.

Por otro lado, el modo binario devuelve bytes y este es el modo que se debe utilizar cuando se trata de archivos que no son de texto, como imágenes o archivos ejecutables.

Modo Descripción
r Abre un archivo para su lectura. (defecto)
w Abre un archivo para escribir. Crea un archivo nuevo si no existe o lo trunca si existe.
x Abre un archivo para creación exclusiva. Si el archivo ya existe, la operación falla.
a Abre un archivo para agregar al final del archivo sin truncarlo. Crea un nuevo archivo si no existe.
t Abre en modo texto. (defecto)
b Abre en modo binario.
+ Abre un archivo para actualizar (lectura y escritura)
 f = open("test.txt") # equivalent to 'r' or 'rt' f = open("test.txt",'w') # write in text mode f = open("img.bmp.webp",'r+b') # read and write in binary mode

A diferencia de otros idiomas, el carácter ano implica el número 97 hasta que se codifica usando ASCII(u otras codificaciones equivalentes).

Además, la codificación predeterminada depende de la plataforma. En Windows, lo es cp1252pero utf-8en Linux.

Por lo tanto, no debemos confiar también en la codificación predeterminada o nuestro código se comportará de manera diferente en diferentes plataformas.

Por lo tanto, cuando se trabaja con archivos en modo texto, es muy recomendable especificar el tipo de codificación.

 f = open("test.txt", mode='r', encoding='utf-8')

Cerrar archivos en Python

Cuando hayamos terminado de realizar operaciones en el archivo, debemos cerrarlo correctamente.

Cerrar un archivo liberará los recursos que estaban vinculados con el archivo. Se realiza mediante el close()método disponible en Python.

Python tiene un recolector de basura para limpiar objetos sin referencia, pero no debemos confiar en él para cerrar el archivo.

 f = open("test.txt", encoding = 'utf-8') # perform file operations f.close()

Este método no es del todo seguro. Si ocurre una excepción cuando estamos realizando alguna operación con el archivo, el código sale sin cerrar el archivo.

Una forma más segura es usar un intento … finalmente bloquear.

 try: f = open("test.txt", encoding = 'utf-8') # perform file operations finally: f.close()

De esta manera, garantizamos que el archivo se cierre correctamente incluso si se genera una excepción que hace que el flujo del programa se detenga.

La mejor forma de cerrar un archivo es mediante la withinstrucción. Esto asegura que el archivo se cierre cuando se sale del bloque dentro de la withdeclaración.

No necesitamos llamar explícitamente al close()método. Se hace internamente.

 with open("test.txt", encoding = 'utf-8') as f: # perform file operations

Escribir en archivos en Python

Para escribir en un archivo en Python, necesitamos abrirlo en modo de escritura w, anexión ao creación exclusiva x.

Debemos tener cuidado con el wmodo, ya que se sobrescribirá en el archivo si ya existe. Debido a esto, se borran todos los datos anteriores.

Writing a string or sequence of bytes (for binary files) is done using the write() method. This method returns the number of characters written to the file.

 with open("test.txt",'w',encoding = 'utf-8') as f: f.write("my first file") f.write("This file") f.write("contains three lines")

This program will create a new file named test.txt in the current directory if it does not exist. If it does exist, it is overwritten.

We must include the newline characters ourselves to distinguish the different lines.

Reading Files in Python

To read a file in Python, we must open the file in reading r mode.

There are various methods available for this purpose. We can use the read(size) method to read in the size number of data. If the size parameter is not specified, it reads and returns up to the end of the file.

We can read the text.txt file we wrote in the above section in the following way:

 >>> f = open("test.txt",'r',encoding = 'utf-8') >>> f.read(4) # read the first 4 data 'This' >>> f.read(4) # read the next 4 data ' is ' >>> f.read() # read in the rest till end of file 'my first fileThis filecontains three lines' >>> f.read() # further reading returns empty sting ''

We can see that the read() method returns a newline as ''. Once the end of the file is reached, we get an empty string on further reading.

We can change our current file cursor (position) using the seek() method. Similarly, the tell() method returns our current position (in number of bytes).

 >>> f.tell() # get the current file position 56 >>> f.seek(0) # bring file cursor to initial position 0 >>> print(f.read()) # read the entire file This is my first file This file contains three lines

We can read a file line-by-line using a for loop. This is both efficient and fast.

 >>> for line in f:… print(line, end = '')… This is my first file This file contains three lines

In this program, the lines in the file itself include a newline character . So, we use the end parameter of the print() function to avoid two newlines when printing.

Alternatively, we can use the readline() method to read individual lines of a file. This method reads a file till the newline, including the newline character.

 >>> f.readline() 'This is my first file' >>> f.readline() 'This file' >>> f.readline() 'contains three lines' >>> f.readline() ''

Lastly, the readlines() method returns a list of remaining lines of the entire file. All these reading methods return empty values when the end of file (EOF) is reached.

 >>> f.readlines() ('This is my first file', 'This file', 'contains three lines')

Python File Methods

There are various methods available with the file object. Some of them have been used in the above examples.

Here is the complete list of methods in text mode with a brief description:

Method Description
close() Closes an opened file. It has no effect if the file is already closed.
detach() Separates the underlying binary buffer from the TextIOBase and returns it.
fileno() Returns an integer number (file descriptor) of the file.
flush() Flushes the write buffer of the file stream.
isatty() Returns True if the file stream is interactive.
read(n) Reads at most n characters from the file. Reads till end of file if it is negative or None.
readable() Returns True if the file stream can be read from.
readline(n=-1) Reads and returns one line from the file. Reads in at most n bytes if specified.
readlines(n=-1) Reads and returns a list of lines from the file. Reads in at most n bytes/characters if specified.
seek(offset,from=SEEK_SET) Changes the file position to offset bytes, in reference to from (start, current, end).
seekable() Returns True if the file stream supports random access.
tell() Returns the current file location.
truncate(size=None) Resizes the file stream to size bytes. If size is not specified, resizes to current location.
writable() Returns True if the file stream can be written to.
write(s) Escribe la cadena s en el archivo y devuelve el número de caracteres escritos.
writeelines (líneas) Escribe una lista de líneas en el archivo.

Articulos interesantes...