ScriptForge.FileSystem service/text/sbasic/shared/03/sf_filesystem.xhpFileSystem service
ScriptForge.FileSystem service
The FileSystem service includes routines to handle files and folders. Next are some examples of the features provided by this service:Verify whether a file or folder exists.Create and delete folders and files.Launch dialog boxes to open/save files.Access the list of files in a folder, etc.The methods in the FileSystem service are mostly based on the XSimpleFileAccess UNO interface.
Definitions
The table below lists the main parameters used by most of the methods in the FileSystem service.
ParameterDescriptionFileNameThe full name of the file including the path without a path separator at the end.FolderNameThe full name of the folder including the path. It may or may not contain the ending path separator.NameThe last component of the Folder Name or File Name including its extension. This parameter is always expressed using the native format of the operating system.BaseNameThe last component of the Folder Name or File Name without its extension.NamePatternAny of the above names containing wildcards in its last component. Admitted wildcards are:"?" represents any single character"*" represents zero, one, or multiple characters
The FileSystem service allows to perform operations over multiple files at the same time. By using name patterns, user scripts can copy, move or delete multiple files. Conversely, Basic built-in methods can only handle single files.
File Naming Notation
The notation used to express file and folder names, both for arguments and returned values, is defined by the FileNaming property of the FileSystem service.In short, the possible representation types are "URL" (URL file notation), "SYS" (operating system notation) and "ANY" (default). See more information below.An example of the URL notation is file:///C:/Documents/my_file.odt. Whenever possible consider using the URL notation because it is a more portable alternative.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".
Service invocation
The following code snippet invokes the FileSystem service. The method BuildPath was used as an example.GlobalScope.BasicLibraries.LoadLibrary("ScriptForge")Dim FSO As ObjectSet FSO = CreateScriptService("FileSystem")FSO.BuildPath(...)from scriptforge import CreateScriptServicefs = CreateScriptService("FileSystem")fs.BuildPath(...)FileSystem service;FileNaming propertyFileSystem service;ConfigFolder propertyFileSystem service;ExtensionsFolder propertyFileSystem service;HomeFolder propertyFileSystem service;InstallFolder propertyFileSystem service;TemplatesFolder propertyFileSystem service;TemporaryFolder propertyFileSystem service;UserTemplatesFolder property
Properties
NameReadonlyTypeDescriptionFileNamingNoStringSets or returns the current files and folders notation, either "ANY", "URL" or "SYS":"ANY": (default) the methods of the FileSystem service accept both URL and current operating system's notation for input arguments but always return URL strings."URL": the methods of the FileSystem service expect URL notation for input arguments and return URL strings."SYS": the methods of the FileSystem service expect current operating system's notation for both input arguments and return strings.Once set, the FileNaming property remains unchanged either until the end of the %PRODUCTNAME session or until it is set again.ConfigFolderYesStringReturns the configuration folder of %PRODUCTNAME.ExtensionsFolderYesStringReturns the folder where extensions are installed.HomeFolderYesStringReturns the user home folder.InstallFolderYesStringReturns the installation folder of %PRODUCTNAME.TemplatesFolderYesStringReturns the folder containing the system templates files.TemporaryFolderYesStringReturns the temporary files folder defined in the %PRODUCTNAME path settings.UserTemplatesFolderYesStringReturns the folder containing the user-defined template files.
List of Methods in the FileSystem Service
BuildPath
CompareFiles
CopyFile
CopyFolder
CreateFolder
CreateTextFile
DeleteFile
DeleteFolder
ExtensionFolder
FileExists
Files
FolderExists
GetBaseName
GetExtension
GetFileLen
GetFileModified
GetName
GetParentFolderName
GetTempName
HashFile
MoveFile
MoveFolder
OpenTextFile
PickFile
PickFolder
SubFolders
Joins a folder path and the name of a file and returns the full file name with a valid path separator. The path separator is added only if necessary.
svc.BuildPath(foldername: str, name: str): str
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.Dim FSO as ObjectSet FSO = CreateScriptService("FileSystem")Dim aFileName as StringFSO.FileNaming = "URL"aFileName = FSO.BuildPath("file:///home/user", "sample file.odt")' file:///home/user/sample%20file.odtfs = CreateScriptService("FileSystem")fs.FileNaming = "URL"aFileName = fs.BuildPath("file:///home/user", "sample file.odt")# file:///home/user/sample%20file.odt CompareFiles ----------------------------------------------------------------------------- FileSystem service;CompareFiles
CompareFiles
Compares two files and returns True when they seem identical.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.
svc.CompareFiles(filename1: str, filename2: str, comparecontents: bool = False): bool
filename1, filename2: The files to compare.comparecontents: When True, the contents of the files are compared (default = False).FSO.FileNaming = "SYS"If FSO.CompareFiles("C:\myFile1.txt", "C:\myFile2.txt", CompareContents := False) Then ' ...End Iffs.FileNaming = "SYS"if fs.CompareFiles(r"C:\myFile1.txt", r"C:\myFile2.txt", comparecontents = False): # ... CopyFile ---------------------------------------------------------------------------------------- FileSystem service;CopyFile
CopyFile
Copies one or more files from one location to another. Returns True if at least one file 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 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.
svc.CopyFile(source: str, destination: str, overwrite: bool = True): bool
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.If destination does not exist, it is created.Wildcard characters are not allowed in destination.overwrite: If True (default), files may be overwritten. The method will fail if destination is readonly, regardless of the value specified in overwrite.In the examples below the first line copies a single file whereas the second line copies multiple files using wildcards.FSO.CopyFile("C:\Documents\my_file.odt", "C:\Temp\copied_file.odt")FSO.CopyFile("C:\Documents\*.*", "C:\Temp\", Overwrite := False)fs.CopyFile(r"C:\Documents\my_file.odt", r"C:\Temp\copied_file.odt")fs.CopyFile(r"C:\Documents\*.*", r"C:\Temp", overwrite = False)Beware that subfolders and their contents are not copied when wildcards are used in the source argument. CopyFolder ----------------------------------------------------------------------------------- FileSystem service;CopyFolder
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.
svc.CopyFolder(source: str, destination: str, overwrite: bool = True): bool
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.If destination does not exist, it is created.Wildcard characters are not allowed in destination.overwrite: If True (default), files may be overwritten. The method will fail if destination is readonly, regardless of the value specified in overwrite.In the examples below all files, folders and subfolders are copied.' BasicFSO.CopyFolder("C:\Documents\*", "C:\Temp\", Overwrite := False)# Pythonfs.CopyFolder(r"C:\Documents\*", r"C:\Temp", overwrite = False) CreateFolder -------------------------------------------------------------------------------------------------------------------------- FileSystem service;CreateFolder
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.
svc.CreateFolder(foldername: str): bool
foldername: A string representing the folder to be created. If the folder already exists, an exception will be raised.' BasicFSO.CreateFolder("C:\NewFolder")# Pythonfs.CreateFolder(r"C:\NewFolder") CreateTextFile ------------------------------------------------------------------------------ FolderSystem service;CreateTextFile
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.
svc.CreateTextFile(filename: str, overwrite: bool = True, encoding: str = 'UTF-8'): svc
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".Dim myFile As ObjectFSO.FileNaming = "SYS"Set myFile = FSO.CreateTextFile("C:\Temp\ThisFile.txt", Overwrite := True)fs.FileNaming = "SYS"myFile = fs.CreateTextFile(r"C:\Temp\ThisFile.txt", overwrite = True)To learn more about the names of character sets, visit IANA's Character Set page. Beware that %PRODUCTNAME does not implement all existing character sets. DeleteFile -------------------------------------------------------------------------------------------------------------------------- FileSystem service;DeleteFile
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.
svc.DeleteFile(filename: str): bool
filename: It can be a FileName or a NamePattern indicating one or more files to be deleted.In the examples below only files are deleted, subfolders are not deleted.' BasicFSO.DeleteFile("C:\Temp\*.docx")# Pythonfs.DeleteFile(r"C:\Temp\*.docx") DeleteFolder -------------------------------------------------------------------------------------------------------------------------- FileSystem service;DeleteFolder
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.
svc.DeleteFolder(foldername: str): bool
foldername: It can be a FolderName or a NamePattern indicating one or more folders to be deleted.In the examples below only folders and their contents are deleted. Files in the parent folder "C:\Temp" are not deleted.' BasicFSO.DeleteFolder("C:\Temp\*")# Pythonfs.DeleteFolder(r"C:\Temp\*") ExtensionFolder --------------------------------------------------------------------------------------- FileSystem service;ExtensionFolder
ExtensionFolder
Returns a string containing the folder where the specified extension package is installed.The current value of the property SF_FileSystem.FileNaming is used to determine the notation of the returned string.Use the property Extensions from the Platform service to get string array with the IDs of all installed extensions.
svc.ExtensionFolder(extension: str): str
extension: A string value with the ID of the extension. If the extension is not installed, an exception is raised.The examples below in Basic and Python return the folder where the APSO extension is installed.' BasicsFolder = 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# PythonsFolder = fs.ExtensionFolder("apso.python.script.organizer") FileExists --------------------------------------------------------------------------------------- FileSystem service;FileExists
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.
svc.FileExists(filename: str): bool
filename: A string representing the file to be tested.FSO.FileNaming = "SYS"If FSO.FileExists("C:\Documents\my_file.odt") Then '...End Iffs.FileNaming = "SYS"if fs.FileExists(r"C:\Documents\my_file.odt"): # ... Files ------------------------------------------------------------------------------------------ FileSystem service;Files
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.
svc.Files(foldername: str, filter: str = ''): str[0..*]
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 = "").Dim filesList As Variant, file As StringFSO.FileNaming = "SYS"filesList = FSO.Files("/home/user/", "*.txt")For Each file In filesList ' ...Next filefs.FileNaming = "SYS"filesList = fs.Files("/home/user/", "*.txt")for file in fileList: # ... FolderExists -------------------------------------------------------------------------------------- FileSystem service;FolderExists
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.
svc.FolderExists(foldername: str): bool
foldername: A string representing the folder to be tested.FSO.FileNaming = "SYS"If FSO.FolderExists("C:\Documents\Thesis") Then '...End Iffs.FileNaming = "SYS"if fs.FolderExists(r"C:\Documents\Thesis") # ... GetBaseName ---------------------------------------------------------------------------------------FileSystem service;GetBaseName
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.
svc.GetBaseName(filename: str): str
filename: A string representing the file name and its path.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.MsgBox FSO.GetBaseName("/home/user/Documents") ' "Documents"MsgBox FSO.GetBaseName("/home/user/Documents/my_file.ods") ' "my_file"bas = CreateScriptService("Basic")bas.MsgBox(fs.GetBaseName("/home/user/Documents")) # "Documents"bas.MsgBox(fs.GetBaseName("/home/user/Documents/my_file.ods")) # "my_file" GetExtension ------------------------------------------------------------------------------------ FileSystem service;GetExtension
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.
svc.GetExtension(filename: str): str
filename: A string representing the file name and its path.' Basicext = FSO.GetExtension("C:\Windows\Notepad.exe") ' "exe"# Pythonext = fs.GetExtension(r"C:\Windows\Notepad.exe") # "exe" GetFileLen ----------------------------------------------------------------------------------- FileSystem service;GetFileLen
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.
svc.GetFileLen(filename: str): num
filename: A string representing an existing file.Dim fLen As CurrencyFSO.FileNaming = "SYS"fLen = FSO.GetFileLen("C:\pagefile.sys")fs.FileNaming = "SYS"fLen = fs.GetFileLen(r"C:\pagefile.sys") GetFileModified -------------------------------------------------------------------------------------------------------------------------- FileSystem service;GetFileModified
GetFileModified
Returns the last modified date of a given file.
svc.GetFileModified(filename: str): datetime
filename: A string representing an existing file.Dim aDate As DateFSO.FileNaming = "SYS"aDate = FSO.GetFileModified("C:\Documents\my_file.odt")fs.FileNaming = "SYS"aDate = FSO.GetFileModified(r"C:\Documents\my_file.odt") GetName -------------------------------------------------------------------------------------------------------------------------- FileSystem service;GetName
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.
svc.GetName(filename: str): str
filename: A string representing the file name and its path.' Basica = FSO.GetName("C:\Windows\Notepad.exe") ' Notepad.exe# Pythona = fs.GetName(r"C:\Windows\Notepad.exe") # Notepad.exe GetParentFolderName -------------------------------------------------------------------------------FileSystem service;GetParentFolderName
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.
svc.GetParentFolderName(filename: str): str
filename: A string with the file or folder name to be analyzed.' Basica = FSO.GetParentFolderName("C:\Windows\Notepad.exe") ' C:\Windows\# Pythona = fs.GetParentFolderName(r"C:\Windows\Notepad.exe") # C:\Windows\ GetTempName ---------------------------------------------------------------------------------------- FileSystem service;GetTempName
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.
svc.GetTempName(): str
Dim fName As StringFSO.FileNaming = "SYS"fName = FSO.GetTempName() & ".txt"' "/tmp/SF_574068.txt"fs.FileNaming = "SYS"fName = FSO.GetTempName() + ".txt"# "/tmp/SF_574068.txt" HashFile -------------------------------------------------------------------------------------- FileSystem service;HashFile
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.
svc.HashFile(filename: str, algorithm: str): str
filename: A string representing an existing file.algorithm: One of the supported algorithms.' BasicsHash = FSO.HashFile("C:\pagefile.sys", "MD5")# PythonsHash = FSO.HashFile(r"C:\pagefile.sys", "MD5") MoveFile -------------------------------------------------------------------------------------------- FileSystem service;MoveFile
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.
svc.MoveFile(source: str, destination: str): bool
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.In the following examples only files are moved, subfolders are not.' BasicFSO.MoveFile("C:\Temp1\*.*", "C:\Temp2")# Pythonfs.MoveFile(r"C:\Temp1\*.*", r"C:\Temp2") MoveFolder --------------------------------------------------------------------------------------- FolderSystem service;MoveFolder
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.
svc.MoveFolder(source: str, destination: str): bool
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.' BasicFSO.MoveFolder("C:\Temp1\*", "C:\Temp2")# Pythonfs.MoveFolder(r"C:\Temp1\*", r"C:\Temp2") OpenTextFile ----------------------------------------------------------------------------------------- FolderSystem service;OpenTextFile
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.
svc.OpenTextFile(filename: str, iomode: int = 1, create: bool = False, encoding: str = 'UTF-8'): svc
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:If True a new file and its parent folders will be created if they do not exist;If False then new files are not created (default).encoding: The character set to be used. The default encoding is "UTF-8".Dim myFile As ObjectFSO.FileNaming = "SYS"Set myFile = FSO.OpenTextFile("C:\Temp\ThisFile.txt", FSO.ForReading)If Not IsNull(myFile) Then ' ...End Iffs.FileNaming = "SYS"myFile = fs.OpenTextFile(r"C:\Temp\ThisFile.txt", fs.ForReading)if myFile is not None: # ... PickFile --------------------------------------------------------------------------------------------- FileSystem service;PickFile
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.
svc.PickFile(defaultfile: str ='', mode: str = 'OPEN', filter: str = ''): str
defaultfile: This argument is a string composed of a folder and file name:The folder part indicates the folder that will be shown when the dialog opens (default = the last selected folder).The file part designates the default file to open or save.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).The examples below open a file picker with the "txt" filter applied.' BasicaFile = FSO.PickFile("C:\Documents", "OPEN", "txt")# PythonaFile = fs.PickFile(r"C:\Documents", "OPEN", "txt") PickFolder ---------------------------------------------------------------------------------------- FileSystem service;PickFolder
PickFolder
Opens a dialog box to select a folder.
svc.PickFolder(defaultfolder: str = '', freetext: str = ''): str
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 = "").' BasicaFolder = FSO.PickFolder("C:\Documents", "Choose a folder or press Cancel")# PythonaFolder = fs.PickFolder(r"C:\Documents", "Choose a folder or press Cancel") SubFolders ---------------------------------------------------------------------------------------- FileSystem service;Files
SubFolders
Returns a zero-based array of strings corresponding to the folders stored in a given foldername.The list may be filtered with wildcards.
svc.SubFolders(foldername: str, filter: str = ''): str[0..*]
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 = "").Dim folderList As Variant, folder As StringFSO.FileNaming = "SYS"folderList = FSO.SubFolders("/home/user/")For Each folder In folderList ' ...Next folderfs.FileNaming = "SYS"folderList = fs.SubFolders("/home/user/")for folder in folderList: # ...