logo

Módulo StringIO en Python

Es el CadenaIO El módulo es un objeto similar a un archivo en memoria. Puede usarse para ingresar o generar la mayoría de las funciones que los usuarios pueden esperar de un objeto de archivo normal. Una vez que el usuario crea los objetos StringIO, inicialmente se crea proporcionando una cadena al constructor. Si no hay ninguna cadena, StringIO estará vacío. En ambos casos, el cursor que se muestra inicialmente en el archivo comenzará en cero.

El módulo no está disponible en la versión más reciente de Python; por lo tanto, para poder utilizar este módulo, debemos transferirlo al módulo Io en Python en el formato io.StringIO.

Ejemplo:

 # First, we will import the required module. from io import StringIO as SIO # The arbitrary string. string_1 = 'This is the initialized string.' # Here, we will use the StringIO method for setting as the file object. # Now, we have an object-file that we can treat as a file. file_1 = SIO(string_1) # Now, we will be reading the file by using read() print (file_1.read()) # Here, We can also write in this file. file_1.write(' Welcome to Javatpoint.com.') # by using the following command, we can make the cursor at index 0. file_1.seek(0) # by using the following command, the user is able to print the file after writing #in the initialized string (string_1). print ('The file of the string after writing in it is:', file_1.read()) 

Producción:

que es un monitor
 This is the initialized string. The file of the string after writing in it is: This is the initialized string. Welcome to Javatpoint.com. 

Métodos importantes de StringIO:

A continuación se muestran algunos métodos de StringIO:

1. StringIO.getvalue(): Esta función se utiliza para devolver el contenido completo del archivo.

Sintaxis:

La sintaxis del método anterior es:

 File_name.getvalue() 

Ejemplo:

 # First, we will import the StringIO module. from io import StringIO as SIO # The arbitrary string. string_1 = 'Hello and thank you for visiting to Javatpoint.com.' # Here, we will use the StringIO method for setting as the file object. file_1 = SIO(string_1) # Retrieving the complete contents of the above file. print(file_1.getvalue()) 

Producción:

trimestres en el año
 Hello and thank you for visiting to Javatpoint.com 

2. En esto, analizamos algunas de las funciones de StringIO que devuelven un valor booleano, es decir, falso o verdadero:

    isatty():Esta función de StringIO se utiliza para devolver False si la transmisión no es interactiva y True si la transmisión es interactiva.legible():Esta función de StringIO se utiliza para devolver False si el archivo no es legible y True si el archivo es legible.escribible():Esta función de StringIO se utiliza para devolver False si el archivo no admite la escritura y True si el archivo admite la escritura.buscable():Esta función de StringIO se utiliza para devolver False si el archivo no admite acceso aleatorio y True si el archivo admite acceso aleatorio.cerrado:Esta función de StringIO se utiliza para devolver False en caso de que el archivo esté abierto y devuelve True si el archivo está cerrado.

Sintaxis:

La sintaxis del método anterior es:

 1. File_name.isatty() 2. File_name.readable() 3. File_name.writable() 4. File_name.seekable() 5. File_name.closed 

Ejemplo:

 # First, we will import the StringIO module. from io import StringIO as SIO # The arbitrary string. string_1 = 'Hello and thank you for visiting to Javatpoint.com.' # Here, we will use the StringIO method for setting # as the file object. file_1 = SIO(string_1) # by using the following command, the user will be able to return is the file #interactive or not. print ('Is the file stream above interactive?', file_1.isatty()) # by using the following command, # the user will be able to return is the file readable or not. print ('Is the file stream above readable?', file_1.readable()) # by using the following command, # the user will be able to return does the file support writing or not. print ('Is the file stream above writable?', file_1.writable()) # by using the following command, , the user will be able to return is the file #seekable or not. print ('Is the file stream above seekable?', file_1.seekable()) # by using the following command, the user will be able to return is the file #closed or not. print ('Is the file above closed?', file_1.closed) 

Producción:

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

3. StringIO.seek(): El buscar() La función se utiliza para establecer la posición del cursor dentro del archivo. Si ejecutamos cualquier operación de escritura o lectura en un documento, el cursor se coloca en el índice que se utilizó por última vez para que podamos mover el cursor desde la posición inicial del archivo. Se emplea seek().

Sintaxis:

La sintaxis del método anterior es:

programa de matriz bidimensional en c
 File_name.seek(argument) #This argument tells the function where to place the cursor. 

Ejemplo:

 # First, we will import the StringIO module. from io import StringIO as SIO # The arbitrary string. string_1 ='Hello and thank you for visiting to Javatpoint.com.' # Here, we will use the StringIO method for setting as the file object. file_1 = SIO(string_1) # here, the user will be able to Read the file: print (file_1.read()) #If the user wishes to view the file again, it will display empty file since the #cursor has been set to the last index. It will also not print anything because #the function returns an empty string. print (file_1.read()) # So, to set the cursor position for reading or writing the file again # we can use seek() function. #We can pass any index here form(0 to len(file)) file_1.seek(0) # Now the user can read the file again print (file_1.read())S 

Producción:

 Hello and thank you for visiting to Javatpoint.com. Hello and thank you for visiting to Javatpoint.com. 

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

Sintaxis:

La sintaxis del método anterior es:

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

Ejemplo:

 # First, we will import the StringIO module. from io import StringIO as SIO # The arbitrary string. string_1 ='Hello and welcome to Javatpoint.com.' # Here, we will use the StringIO method for setting as the file object. file_1 = SIO(string_1) # here, we can read the initial file: print(file_1.read()) # for setting the cursor at 0. file_1.seek(0) # for dropping the file after the given index, i.e., 14. file_1.truncate(14) # here, it will print the File after truncate. print(file_1.read()) 

Producción:

 Hello and welcome to Javatpoint.com. Hello and welc 

5. StringIO.tell(): Este método se utiliza para indicar la secuencia actual del archivo y la posición del cursor.

Sintaxis:

La sintaxis del método anterior es:

 File_name.tell() 

Ejemplo:

 # First, we will import the StringIO module. from io import StringIO as SIO # The arbitrary string. string_1 ='Hello and welcome to Javatpoint.com.' # Here, we will use the StringIO method for setting as the file object. file_1 = SIO(string_1) # Here the cursor is set at index '0'. print(file_1.tell()) # now, we are setting the Cursor to index '23'. file_1.seek(23) # here, we will be printing the index of cursor print(file_1.tell()) 

Producción:

 0 23 

6. CadenaIO.cerrar() Esto se utiliza para cerrar el archivo. Esta función se llama en un archivo y no podemos realizar ninguna operación en él. Cualquier operación que se realice resultará en un Error de valor .

Sintaxis: =

c ++ convierte int a cadena

La sintaxis del método anterior es:

 File_name.close( 

Ejemplo:

 # First, we will import the StringIO module. from io import StringIO as SIO # The arbitrary string. string_1 ='Hello and welcome to Javatpoint.com.' # Here, we will use the StringIO method for setting as the file object. file_1 = SIO(string_1) # here, we can read the initial file: print(file_1.read()) # for closing the current file. file_1.close() # If the user would perform any operation on the above file now, it will raise an #ValueError. # here, we will be using the closed function to know whether the file is closed #or not. print('Is the file closed?', file_1.closed) 

Producción:

 Hello and welcome to Javatpoint.com. Is the file closed? True