ScriptForge.FileSystem serviço

O serviço FileSystem inclui rotinas para gerir ficheiros e pastas. Seguem-se alguns exemplos das funcionalidades disponibilizadas por este serviço:

Ícone de nota

Os métodos do serviço FileSystem baseiam-se, na sua maioria, na interface UNO XSimpleFileAccess.


Definições

A tabela abaixo apresenta os principais parâmetros utilizados pela maioria dos métodos do serviço FileSystem.

Parâmetros

Descrição

FileName

O nome completo do ficheiro, incluindo o caminho, sem um separador de caminho no final.

FolderName

O nome completo da pasta, incluindo o caminho. Pode ou não conter o separador de fim de caminho.

Name

O último componente do Nome da pasta ou Nome do ficheiro, incluindo a sua extensão. Este parâmetro é sempre expresso utilizando o formato nativo do sistema operativo.

BaseName

O último componente do Nome da pasta ou do Nome do ficheiro, sem a extensão.

NamePattern

Qualquer um dos nomes acima que contenha caracteres curinga no seu último componente. Os caracteres curinga permitidos são:

  • "?" representa qualquer carácter único

  • "*" representa zero, um ou vários caracteres


Ícone da dica

O serviço FileSystem permite realizar operações em vários ficheiros ao mesmo tempo. Através da utilização de padrões de nomes, os scripts do utilizador podem copiar, mover ou eliminar vários ficheiros. Por outro lado, os métodos integrados do Basic só conseguem lidar com ficheiros individuais.


Notação para a denominação de ficheiros

A notação utilizada para expressar nomes de ficheiros e pastas, tanto para argumentos como para valores devolvidos, é definida pela propriedade FileNaming do serviço FileSystem.

Em resumo, os tipos de representação possíveis são «URL» (notação de ficheiro URL), «SYS» (notação do sistema operativo) e «ANY» (predefinição). Consulte mais informações abaixo.

Ícone da dica

Um exemplo da notação URL é file:///C:/Documents/my_file.odt. Sempre que possível, considere utilizar a notação URL, pois é uma alternativa mais portátil.


Ícone de aviso

A utilização do atalho «~» (tilde), comum em sistemas operativos baseados em Linux, não é suportada para indicar o caminho para uma pasta e o nome de um ficheiro. Em vez de utilizar «~/Documents/my_file.odt», utilize o caminho completo «/home/user/Documents/my_file.odt».


Chamada de serviço

O seguinte fragmento de código invoca o serviço FileSystem. O método BuildPath foi utilizado como exemplo.

Em Basic

      GlobalScope.BasicLibraries.LoadLibrary("ScriptForge")
      Dim FSO As Object
      Set FSO = CreateScriptService("FileSystem")
      FSO.BuildPath(...)
    
Em Python

      from scriptforge import CreateScriptService
      fs = CreateScriptService("FileSystem")
      fs.BuildPath(...)
    

Aceder ao sistema de ficheiros virtual de um documento

Os ficheiros LibreOffice são ficheiros ZIP comprimidos que contêm os ficheiros e pastas que representam o conteúdo real do documento. Enquanto o documento estiver aberto, é possível aceder a este sistema de ficheiros virtual, explorar a sua estrutura, bem como ler e criar ficheiros e pastas.

O exemplo seguinte mostra como criar um ficheiro de texto com o nome myFile.txt e guardá-lo no sistema de ficheiros virtual do documento.

Em Basic

    GlobalScope.BasicLibraries.LoadLibrary("ScriptForge")
    Dim oDoc As Object, fso As Object, oFile As Object
    Dim sRoot, sFile, sMyDir
    Set fso = CreateScriptService("FileSystem")
    Set oDoc = CreateScriptService("Document", ThisComponent)
    ' Obtém a notação do caminho da URL até à raiz do sistema de ficheiros virtual
    sRoot = oDoc.FileSystem()
    sMyDir = sRoot & "myDir"
    ' Cria a pasta «myDir» caso esta não exista
    If Not fso.FolderExists(sMyDir) Then
        fso.CreateFolder(sMyDir)
    End If
    ' Cria o ficheiro e insere algum texto nele
    sFile = fso.BuildPath(sMyDir, "myFile.txt")
    oFile = fso.CreateTextFile(sFile)
    oFile.WriteLine("Hello!")
    oFile.CloseFile()
  
Em Python

    from scriptforge import CreateScriptService
    bas = CreateScriptService("Basic")
    doc = CreateScriptService("Document", bas.ThisComponent)
    fso = CreateScriptService("FileSystem")
    sRoot = doc.FileSystem
    sMyDir = sRoot + "myDir"
    if not fso.FolderExists(sMyDir):
        fso.CreateFolder(sMyDir)
    sFile = fso.BuildPath(sMyDir, "myFile.txt")
    oFile = fso.CreateTextFile(sFile)
    oFile.WriteLine("Hello!")
    oFile.CloseFile()
  

Em geral, todos os métodos do serviço FileSystem podem ser utilizados para manipular ficheiros no sistema de ficheiros virtual do documento. No entanto, aplicam-se as seguintes restrições:

Ícone de nota

O caminho para o sistema de ficheiros virtual não é um endereço físico no disco rígido do computador. Só é possível aceder-lhe a partir de um script LibreOffice e só existe enquanto o ficheiro do documento estiver aberto.


Propriedades

Nome

Readonly

Tipo

Descrição

FileNaming

Não

String

Define ou devolve a notação atual de ficheiros e pastas, que pode ser «ANY», «URL» ou «SYS»:

  • "ANY": (padrão) os métodos do serviço FileSystem aceitam tanto a notação URL como a notação do sistema operativo atual para os argumentos de entrada, mas devolvem sempre cadeias de caracteres URL.

  • «URL»: os métodos do serviço FileSystem esperam que os argumentos de entrada sigam a notação URL e devolvem cadeias de caracteres do tipo URL.

  • "SYS": os métodos do serviço FileSystem esperam que tanto os argumentos de entrada como as cadeias de caracteres de retorno sigam a notação do sistema operativo atual.

Uma vez definida, a propriedade FileNaming permanece inalterada até ao final da sessão LibreOffice ou até ser definida novamente.

ConfigFolder

Sim

String

Devolve a pasta de configuração do LibreOffice.

ExtensionsFolder

Sim

String

Devolve a pasta onde as extensões estão instaladas.

HomeFolder

Sim

String

Devolve a pasta pessoal do utilizador.

InstallFolder

Sim

String

Devolve a pasta de instalação do LibreOffice.

TemplatesFolder

Yes

String

Devolve a pasta que contém os ficheiros de modelos do sistema.

TemporaryFolder

Sim

String

Devolve a pasta de ficheiros temporários definida nas definições de caminho LibreOffice.

UserTemplatesFolder

Sim

String

Devolve a pasta que contém os ficheiros de modelos definidos pelo utilizador.


Devolve a pasta que contém os ficheiros de modelos definidos pelo utilizador.

BuildPath
CompareFiles
CopyFile
CopyFolder
CreateFolder
CreateTextFile
DeleteFile
DeleteFolder
ExtensionFolder

FileExists
Files
FolderExists
GetBaseName
GetExtension
GetFileLen
GetFileModified
GetName
GetParentFolderName

GetTempName
HashFile
MoveFile
MoveFolder
Normalize
OpenTextFile
PickFile
PickFolder
SubFolders


BuildPath

Junta o caminho de uma pasta ao nome de um ficheiro e devolve o nome completo do ficheiro com um separador de caminho válido. O separador de caminho só é adicionado se for necessário.

Sintaxe:

svc.BuildPath(foldername: str, name: str): str

Parâmetros:

nome-da-pasta: O caminho com o qual nome será combinado. O caminho especificado não precisa de ser uma pasta existente.

nome: O nome do ficheiro a ser acrescentado a nome da pasta. Este parâmetro utiliza a notação do sistema operativo atual.

Exemplo:

Em Basic

      Dim FSO as Object
      Set FSO = CreateScriptService("FileSystem")
      Dim aFileName as String
      FSO.FileNaming = "URL"
      aFileName = FSO.BuildPath("file:///home/user", "sample file.odt")
      ' file:///home/user/sample%20file.odt
    
Em Python

      fs = CreateScriptService("FileSystem")
      fs.FileNaming = "URL"
      aFileName = fs.BuildPath("file:///home/user", "sample file.odt")
      # file:///home/user/sample%20file.odt
    

CompareFiles

Compara dois ficheiros e devolve True quando estes parecem idênticos.

Dependendo do valor do argumento comparecontents, a comparação entre os dois ficheiros pode basear-se apenas nos atributos dos ficheiros (como a data da última modificação) ou no conteúdo dos ficheiros.

Sintaxe:

svc.CompareFiles(filename1: str, filename2: str, comparecontents: bool = False): bool

Parâmetros:

nome_do_ficheiro1, nome_do_ficheiro2: Os ficheiros a comparar.

comparecontents: Quando True, o conteúdo dos ficheiros é comparado (valor predefinido = False).

Exemplo:

Em Basic

      FSO.FileNaming = "SYS"
      If FSO.CompareFiles("C:\myFile1.txt", "C:\myFile2.txt", CompareContents := False) Then
          ' ...
      End If
    
Em Python

      fs.FileNaming = "SYS"
      if fs.CompareFiles(r"C:\myFile1.txt", r"C:\myFile2.txt", comparecontents = False):
          # ...
    

CopyFile

Copia um ou mais ficheiros de um local para outro. Devolve True se pelo menos um ficheiro tiver sido copiado ou False se tiver ocorrido um erro.

Também ocorrerá um erro se o parâmetro source utilizar caracteres curinga e não corresponder a nenhum ficheiro.

O método pára imediatamente após detetar um erro. O método não reverte nem anula as alterações efetuadas antes de o erro ter ocorrido.

Sintaxe:

svc.CopyFile(source: str, destination: str, overwrite: bool = True): bool

Parâmetros:

fonte: Pode ser um FileName ou um NamePattern que indique um ou mais ficheiros a copiar.

destination: It can be either a FileName specifying where the single source file is to be copied, or a FolderName into which the multiple files from source are to be copied.

overwrite: If True (default), files may be overwritten. The method will fail if destination is readonly, regardless of the value specified in overwrite.

Exemplo:

In the examples below the first line copies a single file whereas the second line copies multiple files using wildcards.

Em Basic

      FSO.CopyFile("C:\Documents\my_file.odt", "C:\Temp\copied_file.odt")
      FSO.CopyFile("C:\Documents\*.*", "C:\Temp\", Overwrite := False)
    
Em Python

      fs.CopyFile(r"C:\Documents\my_file.odt", r"C:\Temp\copied_file.odt")
      fs.CopyFile(r"C:\Documents\*.*", r"C:\Temp", overwrite = False)
    
Ícone de nota

Be aware that subfolders and their contents are not copied when wildcards are used in the source argument.


CopyFolder

Copies one or more folders from one location to another. Returns True if at least one folder has been copied or False if an error occurred.

An error will also occur if the source parameter uses wildcard characters and does not match any folders.

The method stops immediately after it encounters an error. The method does not roll back nor does it undo changes made before the error occurred.

Sintaxe:

svc.CopyFolder(source: str, destination: str, overwrite: bool = True): bool

Parâmetros:

source: It can be a FolderName or a NamePattern indicating one or more folders to be copied.

destination: Specifies the FolderName into which the single or multiple folders defined in source are to be copied.

overwrite: If True (default), files may be overwritten. The method will fail if destination is readonly, regardless of the value specified in overwrite.

Exemplo:

In the examples below all files, folders and subfolders are copied.


      ' Basic
      FSO.CopyFolder("C:\Documents\*", "C:\Temp\", Overwrite := False)
    

      # Python
      fs.CopyFolder(r"C:\Documents\*", r"C:\Temp", overwrite = False)
    

CreateFolder

Creates the specified FolderName. Returns True if the folder could be successfully created.

If the specified folder has a parent folder that does not exist, it is created.

Sintaxe:

svc.CreateFolder(foldername: str): bool

Parâmetros:

foldername: A string representing the folder to be created. If the folder already exists, an exception will be raised.

Exemplo:


      ' Basic
      FSO.CreateFolder("C:\NewFolder")
    

      # Python
      fs.CreateFolder(r"C:\NewFolder")
    

CreateTextFile

Creates a specified file and returns a TextStream service instance that can be used to write to the file.

The method returns a Null object if an error occurred.

Sintaxe:

svc.CreateTextFile(filename: str, overwrite: bool = True, encoding: str = 'UTF-8'): svc

Parâmetros:

filename: The name of the file to be created.

overwrite: Boolean value that determines if filename can be overwritten (default = True).

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

Exemplo:

Em Basic

      Dim myFile As Object
      FSO.FileNaming = "SYS"
      Set myFile = FSO.CreateTextFile("C:\Temp\ThisFile.txt", Overwrite := True)
    
Em Python

      fs.FileNaming = "SYS"
      myFile = fs.CreateTextFile(r"C:\Temp\ThisFile.txt", overwrite = True)
    
Ícone de nota

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.


DeleteFile

Deletes one or more files. Returns True if at least one file has been deleted or False if an error occurred.

An error will also occur if the filename parameter uses wildcard characters and does not match any files.

The files to be deleted must not be readonly.

The method stops immediately after it encounters an error. The method does not roll back nor does it undo changes made before the error occurred.

Sintaxe:

svc.DeleteFile(filename: str): bool

Parâmetros:

filename: It can be a FileName or a NamePattern indicating one or more files to be deleted.

Exemplo:

In the examples below only files are deleted, subfolders are not deleted.


      ' Basic
      FSO.DeleteFile("C:\Temp\*.docx")
    

      # Python
      fs.DeleteFile(r"C:\Temp\*.docx")
    

DeleteFolder

Deletes one or more folders. Returns True if at least one folder has been deleted or False if an error occurred.

An error will also occur if the foldername parameter uses wildcard characters and does not match any folders.

The folders to be deleted must not be readonly.

The method stops immediately after it encounters an error. The method does not roll back nor does it undo changes made before the error occurred.

Sintaxe:

svc.DeleteFolder(foldername: str): bool

Parâmetros:

foldername: It can be a FolderName or a NamePattern indicating one or more folders to be deleted.

Exemplo:

In the examples below only folders and their contents are deleted. Files in the parent folder "C:\Temp" are not deleted.


      ' Basic
      FSO.DeleteFolder("C:\Temp\*")
    

      # Python
      fs.DeleteFolder(r"C:\Temp\*")
    

ExtensionFolder

Returns a string containing the folder where the specified extension package is installed.

Ícone de nota

The current value of the property SF_FileSystem.FileNaming is used to determine the notation of the returned string.


Ícone da dica

Use the property Extensions from the Platform service to get string array with the IDs of all installed extensions.


Sintaxe:

svc.ExtensionFolder(extension: str): str

Parâmetros:

extension: A string value with the ID of the extension. If the extension is not installed, an exception is raised.

Exemplo:

The examples below in Basic and Python return the folder where the APSO extension is installed.


      ' Basic
      sFolder = FSO.ExtensionFolder("apso.python.script.organizer")
      ' file:///home/username/.config/libreoffice/4/user/uno_packages/cache/uno_packages/lu10833wz3u2i.tmp_/apso_1_2_7.oxt
    

      # Python
      sFolder = fs.ExtensionFolder("apso.python.script.organizer")
    

FileExists

Returns True if a given file name is valid and exists, otherwise the method returns False.

If the filename parameter is actually an existing folder name, the method returns False.

Sintaxe:

svc.FileExists(filename: str): bool

Parâmetros:

filename: A string representing the file to be tested.

Exemplo:

Em Basic

      FSO.FileNaming = "SYS"
      If FSO.FileExists("C:\Documents\my_file.odt") Then
          '...
      End If
    
Em Python

      fs.FileNaming = "SYS"
      if fs.FileExists(r"C:\Documents\my_file.odt"):
          # ...
    

Files

Returns a zero-based array (BASIC) or tuple (Python) of the files stored in a given folder. Each entry in the array or tuple is a string containing the full path and file name.

If the argument foldername specifies a folder that does not exist, an exception is raised.

The resulting list may be filtered with wildcards.

Sintaxe:

svc.Files(foldername: str, filter: str = '', includesubfolders: bool = False): str[0..*]

Parâmetros:

foldername: A string representing a folder. The folder must exist. This argument must not designate a file.

filter: A string containing wildcards ("?" and "*") that will be applied to the resulting list of files (default = "").

includesubfolders: Set this argument to True to include the contents of subfolders (Default = False).

Exemplo:

Em Basic

      Dim filesList As Variant, file As String
      FSO.FileNaming = "SYS"
      ' Returns all files matching the "*.txt" filter, including files in subfolders
      filesList = FSO.Files("/home/user/", "*.txt", IncludeSubfolders := True)
      For Each file In filesList
          ' ...
      Next file
    
Em Python

      fs.FileNaming = "SYS"
      filesList = fs.Files("/home/user/", "*.txt", includesubfolders = True)
      for file in fileList:
          # ...
    

FolderExists

Returns True if the specified FolderName is valid and exists, otherwise the method returns False.

If the foldername parameter is actually an existing file name, the method returns False.

Sintaxe:

svc.FolderExists(foldername: str): bool

Parâmetros:

foldername: A string representing the folder to be tested.

Exemplo:

Em Basic

      FSO.FileNaming = "SYS"
      If FSO.FolderExists("C:\Documents\Thesis") Then
          '...
      End If
    
Em Python

      fs.FileNaming = "SYS"
      if fs.FolderExists(r"C:\Documents\Thesis")
          # ...
    

GetBaseName

Returns the BaseName (equal to the last component) of a folder or file name, without its extension.

The method does not check if the specified file or folder exists.

Sintaxe:

svc.GetBaseName(filename: str): str

Parâmetros:

filename: A string representing the file name and its path.

Exemplo:

In the examples below, the first GetBaseName method call corresponds to a folder, so the function returns the last component of the path. The second call receives a file name as input, so the name of the file is returned without its extension.

Em Basic

      MsgBox FSO.GetBaseName("/home/user/Documents") ' "Documents"
      MsgBox FSO.GetBaseName("/home/user/Documents/my_file.ods") ' "my_file"
    
Em Python

      bas = CreateScriptService("Basic")
      bas.MsgBox(fs.GetBaseName("/home/user/Documents")) # "Documents"
      bas.MsgBox(fs.GetBaseName("/home/user/Documents/my_file.ods")) # "my_file"
    

GetExtension

Returns the extension part of a file or folder name without the dot "." character.

The method does not check for the existence of the specified file or folder.

If this method is applied to a folder name or to a file without an extension, then an empty string is returned.

Sintaxe:

svc.GetExtension(filename: str): str

Parâmetros:

filename: A string representing the file name and its path.

Exemplo:


      ' Basic
      ext = FSO.GetExtension("C:\Windows\Notepad.exe")  ' "exe"
    

      # Python
      ext = fs.GetExtension(r"C:\Windows\Notepad.exe")  # "exe"
    

GetFileLen

The builtin FileLen Basic function returns the number of bytes contained in a file as a Long value, i.e. up to 2GB.

The GetFileLen method can handle files with much larger sizes by returning a Currency value.

Sintaxe:

svc.GetFileLen(filename: str): num

Parâmetros:

filename: A string representing an existing file.

Exemplo:

Em Basic

      Dim fLen As Currency
      FSO.FileNaming = "SYS"
      fLen = FSO.GetFileLen("C:\pagefile.sys")
    
Em Python

      fs.FileNaming = "SYS"
      fLen = fs.GetFileLen(r"C:\pagefile.sys")
    

GetFileModified

Returns the last modified date of a given file.

Sintaxe:

svc.GetFileModified(filename: str): datetime

Parâmetros:

filename: A string representing an existing file.

Exemplo:

Em Basic

      Dim aDate As Date
      FSO.FileNaming = "SYS"
      aDate = FSO.GetFileModified("C:\Documents\my_file.odt")
    
Em Python

      fs.FileNaming = "SYS"
      aDate = FSO.GetFileModified(r"C:\Documents\my_file.odt")
    

GetName

Returns the last component of a file or folder name in native operating system format.

The method does not check if the specified file or folder exists.

Sintaxe:

svc.GetName(filename: str): str

Parâmetros:

filename: A string representing the file name and its path.

Exemplo:


      ' Basic
      a = FSO.GetName("C:\Windows\Notepad.exe")  ' Notepad.exe
    

      # Python
      a = fs.GetName(r"C:\Windows\Notepad.exe")  # Notepad.exe
    

GetParentFolderName

Returns a string containing the name of the parent folder of a specified file or folder name.

The method does not check if the specified file or folder exists.

Sintaxe:

svc.GetParentFolderName(filename: str): str

Parâmetros:

filename: A string with the file or folder name to be analyzed.

Exemplo:


      ' Basic
      a = FSO.GetParentFolderName("C:\Windows\Notepad.exe")  ' C:\Windows\
    

      # Python
      a = fs.GetParentFolderName(r"C:\Windows\Notepad.exe")  # C:\Windows\
    

GetTempName

Returns a randomly generated temporary file name that is useful for performing operations that require a temporary file.

By default, the returned file name does not have an extension. Use the extension parameter to specify the extension of the file name to be generated.

The folder part of the returned string is the system's temporary folder.

The method does not create the temporary file.

Sintaxe:

svc.GetTempName(extension: str): str

Parâmetros:

extension: The extension of the temporary file name (Default = "").

Exemplo:

Em Basic

      Dim fName As String
      FSO.FileNaming = "SYS"
      fName = FSO.GetTempName(Extension := "txt")
      ' "/tmp/SF_574068.txt"
    
Em Python

      fs.FileNaming = "SYS"
      fName = FSO.GetTempName(extension = "txt")
      # "/tmp/SF_574068.txt"
    

HashFile

Hash functions are used by some cryptographic algorithms, in digital signatures, message authentication codes, fraud detection, fingerprints, checksums (message integrity check), hash tables, password storage and much more.

The HashFile method returns the result of a hash function, applied on a given file and using a specified algorithm. The returned value is a string of lower-case hexadecimal digits.

The hash algorithms supported are: MD5, SHA1, SHA224, SHA256, SHA384 and SHA512.

Sintaxe:

svc.HashFile(filename: str, algorithm: str): str

Parâmetros:

filename: A string representing an existing file.

algorithm: One of the supported algorithms.

Exemplo:


      ' Basic
      sHash = FSO.HashFile("C:\pagefile.sys", "MD5")
    

      # Python
      sHash = FSO.HashFile(r"C:\pagefile.sys", "MD5")
    

MoveFile

Moves one or more files from one location to another. Returns True if at least one file has been moved or False if an error occurred.

An error will also occur if the source parameter uses wildcard characters and does not match any files.

The method stops immediately after it encounters an error. The method does not roll back nor does it undo changes made before the error occurred.

Sintaxe:

svc.MoveFile(source: str, destination: str): bool

Parâmetros:

source: It can be a FileName or NamePattern to designate one or more files to be moved.

destination: If source is a FileName then this parameter indicates the new path and file name of the moved file.

If the move operation involves multiple files, then destination must be a folder name. If it does not exist, it is created.

If source and destination have the same parent folder, the method will rename the source.

Wildcard characters are not allowed in destination.

Exemplo:

In the following examples only files are moved, subfolders are not.


      ' Basic
      FSO.MoveFile("C:\Temp1\*.*", "C:\Temp2")
    

      # Python
      fs.MoveFile(r"C:\Temp1\*.*", r"C:\Temp2")
    

MoveFolder

Moves one or more folders from one location to another. Returns True if at least one folder has been moved or False if an error occurred.

An error will also occur if the source parameter uses wildcard characters and does not match any folders.

The method stops immediately after it encounters an error. The method does not roll back nor does it undo changes made before the error occurred.

Sintaxe:

svc.MoveFolder(source: str, destination: str): bool

Parâmetros:

source: It can be a FolderName or NamePattern to designate one or more folders to be moved.

destination: If the move operation involves a single folder, then destination is the name and path of the moved folder and it must not exist.

If multiple folders are being moved, then destination designates where the folders in source will be moved into. If destination does not exist, it is created.

Wildcard characters are not allowed in destination.

Exemplo:


      ' Basic
      FSO.MoveFolder("C:\Temp1\*", "C:\Temp2")
    

      # Python
      fs.MoveFolder(r"C:\Temp1\*", r"C:\Temp2")
    

Normalize

Returns a string containing the normalized path name by collapsing redundant separators and up-level references.

For instance, the path names A//B, A/B/, A/./B and A/foo/../B are all normalized to A/B.

On Windows, forward slashes "/" are converted to backward slashes "\".

Ícone de nota

The current value of the property SF_FileSystem.FileNaming is used to determine the notation of the filename argument as well as the format of the returned string.


Sintaxe:

svc.Normalize(filename: str): str

Parâmetros:

filename: a string representing a valid path name. The file or directory represented by this argument may not exist.

Exemplo:

Em Basic

    FSO.FileNaming = "URL"
    ' file:///home/user/Documents
    normPath = FSO.Normalize("file:///home/user/Documents/")
    ' file:///home/user/Documents
    normPath = FSO.Normalize("file:///home//user//Documents/")
    ' file:///home/user
    normPath = FSO.Normalize("file:///home//user//Documents/../")
  
Em Python

    fs.FileNaming = "URL"
    normPath = fs.Normalize("file:///home/user/Documents/")
    normPath = fs.Normalize("file:///home//user//Documents/")
    normPath = fs.Normalize("file:///home//user//Documents/../")
  

OpenTextFile

Opens a file and returns a TextStream object that can be used to read from, write to, or append to the file.

Note that the method does not check if the given file is really a text file.

The method returns a Null object (in Basic) or None (in Python) if an error occurred.

Sintaxe:

svc.OpenTextFile(filename: str, iomode: int = 1, create: bool = False, encoding: str = 'UTF-8'): svc

Parâmetros:

filename: Identifies the file to open.

iomode: Indicates the input/output mode. It can be one of three constants: svc.ForReading (default), svc.ForWriting, or svc.ForAppending.

create: Boolean value that indicates whether a new file can be created if the specified filename doesn't exist:

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

Exemplo:

Em Basic

      Dim myFile As Object
      FSO.FileNaming = "SYS"
      Set myFile = FSO.OpenTextFile("C:\Temp\ThisFile.txt", FSO.ForReading)
      If Not IsNull(myFile) Then
          ' ...
      End If
    
Em Python

      fs.FileNaming = "SYS"
      myFile = fs.OpenTextFile(r"C:\Temp\ThisFile.txt", fs.ForReading)
      if myFile is not None:
          # ...
    

PickFile

Opens a dialog box to open or save files.

If the SAVE mode is set and the picked file exists, a warning message will be displayed.

Sintaxe:

svc.PickFile(defaultfile: str ='', mode: str = 'OPEN', filter: str = ''): str

Parâmetros:

defaultfile: This argument is a string composed of a folder and file name:

mode: A string value that can be either "OPEN" (for input files) or "SAVE" (for output files). The default value is "OPEN".

filter: The extension of the files displayed when the dialog is opened (default = no filter).

Exemplo:

The examples below open a file picker with the "txt" filter applied.


      ' Basic
      aFile = FSO.PickFile("C:\Documents", "OPEN", "txt")
    

      # Python
      aFile = fs.PickFile(r"C:\Documents", "OPEN", "txt")
    

PickFolder

Opens a dialog box to select a folder.

Sintaxe:

svc.PickFolder(defaultfolder: str = '', freetext: str = ''): str

Parâmetros:

defaultfolder: A string containing the folder name that will be displayed when the dialog is opened (default = the last selected folder).

freetext: Text to display in the dialog (default = "").

Exemplo:


      ' Basic
      aFolder = FSO.PickFolder("C:\Documents", "Choose a folder or press Cancel")
    

      # Python
      aFolder = fs.PickFolder(r"C:\Documents", "Choose a folder or press Cancel")
    

SubFolders

Returns a zero-based array of strings corresponding to the folders stored in a given foldername.

The list may be filtered with wildcards.

Sintaxe:

svc.SubFolders(foldername: str, filter: str = '', includesubfolders: bool = False): str[0..*]

Parâmetros:

foldername: A string representing a folder. The folder must exist. foldername must not designate a file.

filter: A string containing wildcards ("?" and "*") that will be applied to the resulting list of folders (default = "").

includesubfolders: Set this argument to True to include the contents of subfolders (Default = False).

Exemplo:

Em Basic

      Dim folderList As Variant, folder As String
      FSO.FileNaming = "SYS"
      folderList = FSO.SubFolders("/home/user/")
      For Each folder In folderList
          ' ...
      Next folder
    
Em Python

      fs.FileNaming = "SYS"
      folderList = fs.SubFolders("/home/user/")
      for folder in folderList:
          # ...
    
Ícone de aviso

Todas as rotinas ou identificadores do ScriptForge Basic que tenham o caractere de sublinhado «_» como prefixo estão reservados para uso interno. Não se destinam a ser utilizados em macros do Basic ou em scripts Python.


Necessitamos da sua ajuda!

Necessitamos da sua ajuda!