Tenesta ScriptForge.FileSystem

Tenesta FileSystem inneheld rutinar for handsaming av filer og mapper. Her kjem nokre eksempel på funksjonane som vert leverte av denne tenesta:

note

Metodane i tenesta FileSystem er for det meste basert på XSimpleFileAccess UNO interface.


Definisjonar

Tabellen nedanfor viser hovudparameterane som vert brukte av dei fleste metodane i FileSystem-tenestene.

Parameter

Beskriving

FileName

Det fullstendige namnet på filen, inkludert stien utan eit stiskiljeteikn til slutt.

FolderName

Det fullstendige namnet på mappa, inkludert stien. Det kan innehalda eller ikkje innehalda det avsluttande stiskilleteiknet.

Name

Den siste komponenten i mappenamnet eller filnamnet inkludert utvidinga. Denne parameteren vert alltid sett med formatet brukt i operativsystemet.

BaseName

Den siste komponenten i mappenamnet eller filnamnet utan utvidinga.

NamePattern

Nokre av namna ovanfor inneheld jokerteikn i den siste komponenten. Tillatne jokerteikn er:

  • "?" stÃ¥r for eitt enkelt teikn

  • "*" stÃ¥r for ingen, eitt eller fleire teikn


tip

Tenesta FileSystem gjer det mogleg å utføra operasjonar på fleire filer samstundes. Ved hjelp av namnemønster kan brukarskript kopiera, flytta eller slette fleire filer. På den annen sida kan grunnleggjande innebygde metodar berre handsama enkeltfiler.


Notasjon for filnamn

Notasjonen som vert brukt for å uttrykkja fil- og mappe-namn, både i argumenta og returverdiane, er definerte av eigenskapen FileNaming i tenesta FileSystem.

Kort sagt, dei moglege representasjonstypane er «URL» (URL-filnotasjon), «SYS» (operativsystemnotasjon) og «ANY» (standard). Sjå meir informasjon i nedanfor.

tip

Eit eksempel på URL-notasjonen er file:///C:/Documents/my_file.odt. Når det er mogleg, bør du vurdera å bruka URL-notasjonen fordi det er eit meir berbart alternativ.


warning

The use of the shortcut "~" (tilde), which is common in Linux-based operating systems, is not supported to express a path to a folder and file name. Instead of using "~/Documents/my_file.odt" use the full path "/home/user/Documents/my_file.odt".


Oppkall av tenester

Den neste kodesnutten kallar opp tenesta FileSystem. Metoden BuildPath er brukt som eksempel.

I Basic

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

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

Eigenskapar

Namn

Skriveverna

Type

Beskriving

FileNaming

Nei

String

Set eller returnerer gjeldande fil- og mappenotasjon, anten «ANY», «URL» eller «SYS»:

  • "ANY": (standard) metodane i tenesta FileSystem godtar bÃ¥de URL-adressa og gjeldande operativsystemnotasjon for inndataargument, men returnerer alltid URL-strengar.

  • "URL": metodane i tenesta FileSystem ventar URL-notasjon i inndata-argument og returnerer URL-strengar.

  • "SYS": metodane i tenesta FileSystem ventar operativsystemet sin notasjon brukt bÃ¥de i inndata-argument og returnerstrengane.

Når eigenskapen FileNaming er sett, vert han uendra anten til slutten av LibreOffice-økta eller til han vert sett på nytt.

ConfigFolder

Ja

String

Returnerer konfigurasjonsmappa for LibreOffice.

ExtensionsFolder

Ja

String

Returnerer mappa som utvidingane er installerte i.

HomeFolder

Ja

String

Returnerer brukaren si heimemappe.

InstallFolder

Ja

String

Returnerer installasjonsmappa for LibreOffice.

TemplatesFolder

Ja

String

Returnerer mappa som inneheld systemet sine malfiler.

TemporaryFolder

Ja

String

Returnerer mappa til dei mellombels filene som er definerte i LibreOffice sti-innstillingar.

UserTemplatesFolder

Ja

String

Returnerer mappa som inneheld dei brukardefinerte malfilene.


Liste over metodar i tenesta FileSystem

BuildPath
CompareFiles
CopyFile
CopyFolder
CreateFolder
CreateTextFile
DeleteFile
DeleteFolder
FileExists

Files
FolderExists
GetBaseName
GetExtension
GetFileLen
GetFileModified
GetName
GetParentFolderName

GetTempName
HashFile
MoveFile
MoveFolder
OpenTextFile
PickFile
PickFolder
SubFolders


BuildPath

Slår saman ein mappesti og namnet på ei fil og returnerer det fullstendige filnamnet med eit gyldig stikiljeteikn. Stiskiljeteiknet vert lagt til berre om det er nødvendig.

Syntaks:

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

Parametrar:

foldername: The path with which name will be combined. The specified path does not need to be an existing folder.

name: The name of the file to be appended to foldername. This parameter uses the notation of the current operating system.

Eksempel:

I 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
    
I Python

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

CompareFiles

Samanliknar to filer og returnerer Sann når dei ser ut til å vera like.

Depending on the value of the comparecontents argument, the comparison between both files can be either based only on file attributes (such as the last modified date), or based on the file contents.

Syntaks:

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

Parametrar:

filename1, filename2: The files to compare.

comparecontents: When True, the contents of the files are compared (default = False).

Eksempel:

I Basic

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

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

CopyFile

Kopierer éi eller fleire filer frå éin stad til ein annan. Returnerer Sann viss minst éi fil er kopiert, eller Usann viss det skjedde ein feil.

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

Metoden stoppar straks når det oppstår ein feil. Metoden rullar ikkje tilbake, og angrar heller ikkje endringar som vart gjort før feilen oppstod.

Syntaks:

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

Parametrar:

source: It can be a FileName or a NamePattern indicating one or more files to be copied.

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.

Eksempel:

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

I Basic

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

      fso.CopyFile(r"C:\Documents\my_file.odt", r"C:\Temp\copied_file.odt")
      fso.CopyFile(r"C:\Documents\*.*", r"C:\Temp", overwrite = False)
    
note

Beware 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.

Syntaks:

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

Parametrar:

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.

Eksempel:

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


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

      # Python
      fso.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.

Syntaks:

svc.CreateFolder(foldername: str): bool

Parametrar:

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

Eksempel:


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

      # Python
      fso.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.

Syntaks:

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

Parametrar:

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".

Eksempel:

I Basic

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

      fso.FileNaming = "SYS"
      myFile = fso.CreateTextFile(r"C:\Temp\ThisFile.txt", overwrite = True)
    
note

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.


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.

Syntaks:

svc.DeleteFile(filename: str): bool

Parametrar:

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

Eksempel:

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


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

      # Python
      fso.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.

Syntaks:

svc.DeleteFolder(foldername: str): bool

Parametrar:

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

Eksempel:

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
      fso.DeleteFolder(r"C:\Temp\*")
    

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.

Syntaks:

svc.FileExists(filename: str): bool

Parametrar:

filename: A string representing the file to be tested.

Eksempel:

I Basic

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

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

Files

Returns a zero-based array of the files stored in a given folder. Each entry in the array 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.

Syntaks:

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

Parametrar:

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 = "").

Eksempel:

I Basic

      Dim filesList As Variant, file As String
      FSO.FileNaming = "SYS"
      filesList = FSO.Files("/home/user/", "*.txt")
      For Each file In filesList
          ' ...
      Next file
    
I Python

      fso.FileNaming = "SYS"
      filesList = fso.Files("/home/user/", "*.txt")
      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.

Syntaks:

svc.FolderExists(foldername: str): bool

Parametrar:

foldername: A string representing the folder to be tested.

Eksempel:

I Basic

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

      fso.FileNaming = "SYS"
      if fso.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.

Syntaks:

svc.GetBaseName(filename: str): str

Parametrar:

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

Eksempel:

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.

I Basic

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

      bas = CreateScriptService("Basic")
      bas.MsgBox(fso.GetBaseName("/home/user/Documents")) # "Documents"
      bas.MsgBox(fso.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.

Syntaks:

svc.GetExtension(filename: str): str

Parametrar:

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

Eksempel:


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

      # Python
      ext = fso.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.

Syntaks:

svc.GetFileLen(filename: str): num

Parametrar:

filename: A string representing an existing file.

Eksempel:

I Basic

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

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

GetFileModified

Returns the last modified date of a given file.

Syntaks:

svc.GetFileModified(filename: str): datetime

Parametrar:

filename: A string representing an existing file.

Eksempel:

I Basic

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

      fso.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.

Syntaks:

svc.GetName(filename: str): str

Parametrar:

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

Eksempel:


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

      # Python
      a = fso.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.

Syntaks:

svc.GetParentFolderName(filename: str): str

Parametrar:

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

Eksempel:


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

      # Python
      a = fso.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.

The returned file name does not have any suffix. The folder part of the returned string is the system's temporary folder.

The method does not create the temporary file.

Syntaks:

svc.GetTempName(): str

Eksempel:

I Basic

      Dim fName As String
      FSO.FileNaming = "SYS"
      fName = FSO.GetTempName() & ".txt"
      ' "/tmp/SF_574068.txt"
    
I Python

      fso.FileNaming = "SYS"
      fName = FSO.GetTempName() + ".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.

Syntaks:

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

Parametrar:

filename: A string representing an existing file.

algorithm: One of the supported algorithms.

Eksempel:


      ' 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.

Syntaks:

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

Parametrar:

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.

Eksempel:

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


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

      # Python
      fso.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.

Syntaks:

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

Parametrar:

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.

Eksempel:


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

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

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.

Syntaks:

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

Parametrar:

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".

Eksempel:

I 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
    
I Python

      fso.FileNaming = "SYS"
      myFile = fso.OpenTextFile(r"C:\Temp\ThisFile.txt", fso.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.

Syntaks:

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

Parametrar:

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).

Eksempel:

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


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

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

PickFolder

Opens a dialog box to select a folder.

Syntaks:

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

Parametrar:

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 = "").

Eksempel:


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

      # Python
      aFolder = fso.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.

Syntaks:

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

Parametrar:

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 = "").

Eksempel:

I Basic

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

      fso.FileNaming = "SYS"
      folderList = fso.SubFolders("/home/user/")
      for folder in folderList:
          # ...
    
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.