Módulo StringIO en Python

El módulo StringIO es un objeto similar a un archivo en memoria. Este objeto se puede utilizar como entrada o salida para la mayoría de las funciones que esperaría un objeto de archivo estándar. Cuando se crea el objeto StringIO, se inicializa pasando una string al constructor. Si no se pasa ninguna string, StringIO comenzará vacío. En ambos casos, el cursor inicial en el archivo comienza en cero.

NOTA: este módulo no existe en la última versión de Python, por lo que para trabajar con este módulo debemos importarlo desde el módulo io en Python como io.StringIO.

Ejemplo: 

Python3

# Importing the StringIO module.
from io import StringIO 
 
 
# The arbitrary string.
string ='This is initial string.'
 
# Using the StringIO method to set
# as file object. Now we have an
# object file that we will able to
# treat just like a file.
file = StringIO(string)
 
# this will read the file
print(file.read())
 
# We can also write this file.
file.write(" Welcome to geeksforgeeks.")
 
# This will make the cursor at
# index 0.
file.seek(0)
 
# This will print the file after
# writing in the initial string.
print('The string after writing is:', file.read())

Producción:

Esta es la string inicial. 
La string después de escribir es: Esta es la string inicial. Bienvenido a geeksforgeeks.

Algunos de los métodos importantes de StringIO son los siguientes:

1. StringIO.getvalue(): esta función devuelve todo el contenido del archivo.
 

Sintaxis: 

File_name.getvalue()

Ejemplo: 

Python3

# Importing the StringIO module.
from io import StringIO 
 
 
# The arbitrary string.
string ='Hello and welcome to GeeksForGeeks.'
 
# Using the StringIO method to
# set as file object.
file = StringIO(string)
 
# Retrieve the entire content of the file.
print(file.getvalue())

Producción: 

'Hello and welcome to GeeksForGeeks.'

2. En esto, discutimos sobre algunas funciones de StringIO que devuelven valores booleanos, es decir, verdadero o falso: 

  • StringIO.isatty(): esta función devuelve verdadero si la transmisión es interactiva y falso si la transmisión no es interactiva
  • StringIO.readable(): esta función devuelve True si el archivo es legible y devuelve False si el archivo no es legible.
  • StringIO.writable(): esta función devuelve True si el archivo admite escritura y devuelve False si el archivo no admite escritura.
  • StringIO.seekable(): esta función devuelve True si el archivo admite acceso aleatorio y devuelve False si el archivo no admite acceso aleatorio.
  • StringIO.closed: esta función devuelve True si el archivo está cerrado y devuelve False si el archivo está abierto.

Sintaxis: 

File_name.isatty()
File_name.readable()
File_name.writable()
File_name.seekable()
File_name.closed

Ejemplo:

Python3

# Importing the StringIO module.
from io import StringIO 
 
 
# The arbitrary string.
string ='Hello and welcome to GeeksForGeeks.'
 
# Using the StringIO method to
# set as file object.
file = StringIO(string)
 
# This will returns whether the file
# is interactive or not.
print("Is the file stream interactive?", file.isatty())
 
# This will returns whether the file is
# readable or not.
print("Is the file stream readable?", file.readable())
 
# This will returns whether the file supports
# writing or not.
print("Is the file stream writable?", file.writable())
 
# This will returns whether the file is
# seekable or not.
print("Is the file stream seekable?", file.seekable())
 
# This will returns whether the file is
# closed or not.
print("Is the file closed?", file.closed)

Producción: 

Is the file stream interactive? False
Is the file stream readable? True
Is the file stream writable? True
Is the file stream seekable? True
Is the file closed? False

3.StringIO.seek(): La función seek() se utiliza para establecer la posición del cursor en el archivo. Si realizamos cualquier operación de lectura y escritura en un archivo, el cursor se coloca en el último índice, por lo que para mover el cursor al índice de inicio del archivo se utiliza seek(). 

Sintaxis: 

File_name.seek(argument) 
# Here the argument is passed to tell the 
# function  where to set the cursor position. 

Ejemplo: 

Python3

# Importing the StringIO module.
from io import StringIO 
 
 
# The arbitrary string.
string ='Hello and welcome to GeeksForGeeks.'
 
# Using the StringIO method
# to set as file object.
file = StringIO(string)
 
# Reading the file:
print(file.read())
 
# Now if we again want to read
# the file it shows empty file
# because the cursor is set to
# the last index.
 
 
# This does not print anything
# because the function returns an
# empty string.
print(file.read())
 
# Hence to set the cursor position
# to read or write the file again
# we use seek().We can pass any index
# here form(0 to len(file))
file.seek(0)
 
# Now we can able to read the file again()
print(file.read())

Producción: 

Hello and welcome to GeeksForGeeks.
Hello and welcome to GeeksForGeeks.

4.StringIO.truncate(): esta función se utiliza para cambiar el tamaño del flujo de archivos. Este método coloca el archivo después del índice proporcionado y lo guarda. 

Sintaxis: 

File_name.truncate(size = None)
# We can provide the size from where 
# to truncate the file.

Ejemplo: 

Python3

# Importing the StringIO module.
from io import StringIO 
 
 
# The arbitrary string.
string ='Hello and welcome to GeeksForGeeks.'
 
# Using the StringIO method
# to set as file object.
file = StringIO(string)
 
# Reading the initial file:
print(file.read())
 
# To set the cursor at 0.
file.seek(0)
 
 
# This will drop the file after
# index 18.
file.truncate(18)
 
# File after truncate.
print(file.read())

Producción: 

Hello and welcome to GeeksForGeeks.
Hello and welcome 

5.StringIO.tell(): este método se usa para indicar la secuencia actual o la posición del cursor del archivo.

Sintaxis: 

File_name.tell()

Ejemplo: 

Python3

# Importing the StringIO module.
from io import StringIO 
 
 
# The arbitrary string.
string ='Hello and welcome to GeeksForGeeks.'
 
# Using the StringIO method to
# set aas file object.
file = StringIO(string)
 
# Here the cursor is at index 0.
print(file.tell())
 
# Cursor is set to index 20.
file.seek(20)
 
# Print the index of cursor
print(file.tell())

Producción: 

0
20

6.StringIO.close(): este método se utiliza para cerrar el archivo. Después de que esta función llame a un archivo, no podemos realizar ninguna operación en el archivo. Si se realiza alguna operación, generará un ValueError.

Sintaxis: 

File_name.close()

Ejemplo: 

Python3

# Importing the StringIO module.
from io import StringIO 
 
 
# The arbitrary string.
string ='Hello and welcome to GeeksForGeeks.'
 
# Using the StringIO method to
# set as file object.
file = StringIO(string)
 
# Reading the file.
print(file.read())
 
# Closing the file.
file.close()
 
# If we now perform any operation on the file
# it will raise an ValueError.
 
# This is to know whether the
# file is closed or not.
print("Is the file closed?", file.closed)

Producción: 

Hello and welcome to GeeksForGeeks.
Is the file closed? True

Publicación traducida automáticamente

Artículo escrito por VishwashVishwakarma y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *