Contenido
Índice 🔎︎

# Servicio ScriptForge.TextStream

El servicio TextStream se utiliza para leer y escribir secuencialmente archivos abiertos mediante el servicio ScriptForge.FileSystem.

Los métodos OpenTextFile y CreateTextFile del servicio FileSystem devuelven una ocurrencia del servicio TextStream.

Line delimiters may be specified by the user. In input operations CR, LF or CR+LF are supported. In output operations, the default line delimiter is the one used by the operating system.

The line delimiter for the operating system where the macro is being executed can be accessed using the SF_String.sfNEWLINE property.

All operations needed to read from or write to a file (open, read/write and close) are presumed to happen during the same macro run.

## Invocación del servicio

Los ejemplos siguientes en BASIC y Python utilizan el método OpenTextFile para crear un ejemplar del servicio TextStream.

##### En BASIC

        GlobalScope.BasicLibraries.LoadLibrary("ScriptForge")
        Dim FSO As Variant
        FSO = CreateScriptService("FileSystem")
        Set myFile = FSO.OpenTextFile("C:\Temp\ThisFile.txt", FSO.ForReading)

El archivo debe cerrarse con el método CloseFile después de que todas las operaciones de lectura o escritura se hayan ejecutado:

        myFile.CloseFile()

Optionally, the resources used by the TextStream instance can be released using the Dispose method:

        Set myFile = myFile.Dispose()

Los métodos del servicio TextStream se basan principalmente en las interfaces XTextInputStream y XTextOutputStream de UNO.

##### En Python

        from scriptforge import CreateScriptService
        fso = CreateScriptService("FileSystem")
        myFile = fso.OpenTextFile(r"C:\Temp\ThisFile.txt", fso.ForReading)
        # ...
        myFile.CloseFile()
        myFile = myFile.Dispose()

## Propiedades

Nombre | De solo lectura | Tipo | Descripción
AtEndOfStream | Sí | Boolean | Se utiliza en el modo de lectura. Un valor True indica que se ha llegado al final del archivo. Una prueba que utilice esta propiedad debe preceder a las llamadas al método ReadLine.
Encoding | Sí | String | El conjunto de caracteres que debe utilizarse. La codificación predeterminada es «UTF-8».
FileName | Sí | String | Returns the name of the current file either in URL format or in the native operating system's format, depending on the current value of the FileNaming property of the FileSystem service.
IOMode | Sí | String | Indica el modo de entrada/salida. Los valores posibles son «READ», «WRITE» y «APPEND».
Line | Sí | Long | Returns the number of lines read or written so far.
NewLine | No | String | Establece o devuelve el delimitador actual que se insertará entre dos renglones escritos sucesivos. El valor predeterminado es el delimitador de renglón nativo del sistema operativo actual.

To learn more about the names of character sets, visit IANA's Character Set page. Beware that LibreOffice does not implement all existing character sets.

Lista de métodos en el servicio TextStream
CloseFile ReadAll | ReadLine SkipLine | WriteBlankLines WriteLine

## CloseFile

Closes the current input or output stream and empties the output buffer if relevant. Returns True if the file was successfully closed.

### Sintaxis:

myFile.CloseFile(): bool

## ReadAll

Returns all the remaining lines in the text stream as a single string. Line breaks are not removed.

The resulting string can be split in lines either by using the Split built-in Basic function if the line delimiter is known, or with the SF_String.SplitLines method.

For large files, using the ReadAll method wastes memory resources. In such cases it is recommended to read the file line by line using the ReadLine method.

### Sintaxis:

myFile.ReadAll(): str

### Ejemplo:

Considere el archivo de texto «Alumnos.txt» con este contenido (un nombre por cada renglón):

        Herbie Peggy
        Hardy Jarrett
        Edith Lorelle
        Roderick Rosamund
        Placid Everette

The examples below in Basic and Python use the ReadAll and SplitLines methods to read the contents of the file into an array of strings:

##### En BASIC

        'Carga el servicio FileSystem
        Dim FSO : FSO = CreateScriptService("FileSystem")
        'Opens the text file with the names to be read
        Dim inputFile as Object
        Set inputFile = FSO.OpenTextFile("/home/user/Documents/Students.txt")
        'Reads all the contents in the input file as a single string
        Dim allData as String
        allData = inputFile.ReadAll()
        'Splits the string into an array
        Dim arrNames as Variant
        arrNames = SF_String.SplitLines(allData)
        ' (...)
        inputFile.CloseFile()

##### En Python

        fso = CreateScriptService("FileSystem")
        inputFile = fso.OpenTextFile("/home/user/Documents/Students.txt")
        allData = inputFile.ReadAll()
        arrNames = allData.split(inputFile.NewLine)
        # ...
        inputFile.CloseFile()

## ReadLine

Returns the next line in the text stream as a string. Line breaks are removed from the returned string.

The AtEndOfStream test should precede the ReadLine method like in the example below.

An error will be raised if the AtEndOfStream was reached during the previous ReadLine or SkipLine method call.

### Sintaxis:

myFile.ReadLine(): str

### Ejemplo:

##### En BASIC

        Dim sLine As String
        Do While Not myFile.AtEndOfStream
            sLine = myFile.ReadLine()
            ' (...)
        Loop

##### En Python

        while not myFile.AtEndOfStream:
            sLine = myFile.ReadLine()
            # ...

## SkipLine

Skips the next line in the input stream when reading a TextStream file.

This method can result in AtEndOfStream being set to True.

### Sintaxis:

myFile.SkipLine()

## WriteBlankLines

Writes a specified number of empty lines to the output stream.

### Sintaxis:

myFile.WriteBlankLines(lines: int)

### Parámetros:

lines: The number of empty lines to write to the file.

## WriteLine

Writes the given string to the output stream as a single line.

El carácter definido en la propiedad NewLine se utiliza como delimitador de renglones.

### Sintaxis:

myFile.WriteLine(line: str)

### Parámetros:

line: The line to write, may be empty.

### Ejemplo:

The examples below in Basic and Python create a text file in CSV format in which each line contains a value and its square until lastValue is reached.

##### En BASIC

        Sub SquaredValuesFile(lastValue as Integer)
            'Instantiates the FileSystem Service
            Dim FSO as Variant : FSO = CreateScriptService("FileSystem")
            'Crea un archivo de texto
            Dim myFile as Variant : myFile = FSO.CreateTextFile("/home/user/Documents/squares.csv")
            'Writes the Value and Value squared, separated by ";"
            Dim value as Integer
            myFile.WriteLine("Value;Value Squared")
            For value = 1 To lastValue
                myFile.WriteLine(value & ";" & value ^ 2)
            Next value
            'Cierra el archivo y libera recursos
            myFile.CloseFile()
            Set myFile = myFile.Dispose()
        End Sub

##### En Python

        def squared_values_file(lastValue):
            fso = CreateScriptService("FileSystem")
            myFile = fso.CreateTextFile("/home/user/Documents/squares.csv")
            myFile.WriteLine("Value;Value Squared")
            for value in range(1, lastValue + 1):
                myFile.WriteLine("{};{}".format(value, value ** 2))
            myFile.CloseFile()
            myFile = myFile.Dispose()

Todas las rutinas o identificadores BASIC de ScriptForge precedidas por guion bajo «_» están reservadas para uso interno. No deben utilizarse en macros BASIC o secuencias Python.

Temas relacionados

Servicio ScriptForge.FileSystem

Input Function [VBA]

Open Statement