ScriptForge.TextStream service

The TextStream service is used to sequentially read from and write to files opened or created using the ScriptForge.FileSystem service.

The methods OpenTextFile and CreateTextFile from the FileSystem service return an instance of the TextStream service.

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.

note

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.


Service invocation

The examples below in Basic and Python use the OpenTextFile method to create an instance of the TextStream Service.

In Basic

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

The file must be closed with the CloseFile method after all read or write operations have been executed:


    myFile.CloseFile()
  

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


    Set myFile = myFile.Dispose()
  
note

The methods in the TextStream service are mostly based on the XTextInputStream and XTextOutputStream UNO interfaces.


In Python

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

Properties

Name

Readonly

Type

Description

AtEndOfStream

Yes

Boolean

Used in read mode. A True value indicates that the end of the file has been reached. A test using this property should precede calls to the ReadLine method.

Encoding

Yes

String

The character set to be used. The default encoding is "UTF-8".

FileName

Yes

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

Yes

String

Indicates the input/output mode. Possible values are "READ", "WRITE" or "APPEND".

Line

Yes

Long

Returns the number of lines read or written so far.

NewLine

No

String

Sets or returns the current delimiter to be inserted between two successive written lines. The default value is the native line delimiter in the current operating system.


note

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


List of Methods in the TextStream Service

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.

Syntax:

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.

Syntax:

myFile.ReadAll(): str

Example:

Consider the text file "Students.txt" with the following contents (a name in each line):


    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:

In Basic

    'Loads the FileSystem service
    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()
  
In Python

    fs = CreateScriptService("FileSystem")
    inputFile = fs.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.

Syntax:

myFile.ReadLine(): str

Example:

In Basic

    Dim sLine As String
    Do While Not myFile.AtEndOfStream
        sLine = myFile.ReadLine()
        ' (...)
    Loop
  
In 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.

Syntax:

myFile.SkipLine()

WriteBlankLines

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

Syntax:

myFile.WriteBlankLines(lines: int)

Parameters:

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

WriteLine

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

The character defined in the NewLine property is used as the line delimiter.

Syntax:

myFile.WriteLine(line: str)

Parameters:

line: The line to write, may be empty.

Example:

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.

In Basic

    Sub SquaredValuesFile(lastValue as Integer)
        'Instantiates the FileSystem Service
        Dim FSO as Variant : FSO = CreateScriptService("FileSystem")
        'Creates a text file
        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
        'Closes the file and free resources
        myFile.CloseFile()
        Set myFile = myFile.Dispose()
    End Sub
  
In Python

    def squared_values_file(lastValue):
        fs = CreateScriptService("FileSystem")
        myFile = fs.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()
  
warning

All ScriptForge Basic routines or identifiers that are prefixed with an underscore character "_" are reserved for internal use. They are not meant be used in Basic macros or Python scripts.


Please support us!