File and Folder Interaction
Your SenseTalk scripts can interact with files and file system objects in a variety of ways. For instance, you can read stored data from a file on the local machine, then use that data to perform additional actions. In most cases, we recommend using the first method, described below in Accessing a File as a Container, for reading and writing to files.
SenseTalk commands and functions for working with files and file system objects operate on the local machine rather than on a system under test (SUT).
To understand how to refer to a file or folder or to access information about files and folders, see File and Folder References.
As a best practice, any files referenced within a SenseTalk script should be added to Eggplant Functional through the Resources pane in the Suite window. This method stores files to the Resources directory within the suite directory for the given suite. Although SenseTalk can access files stored elsewhere on the local file system, using the Resources directory provides additional capabilities. See the Resources Pane for more information.
Accessing a File as a Container
The simplest way to work with the contents of a file is to access the file directly as a SenseTalk container using a file
expression. Using this approach, you can read an entire file with a single command:
put file "/etc/passwd" into passwordInfo
You can write a file just as easily:
put "0,0,0,0" into file "/tmp/testing/counters"
The command above creates a file named counters
in the directory /tmp/testing
and writes the value 0,0,0,0
into it. If the /tmp/testing
directory does not exist, it is also created. If there is already a file /tmp/testing/counters
, its previous contents are completely replaced by the new value, so be careful when using this approach.
You can also access any part of the text in a file by using chunk expressions:
add 1 to item 2 of line 1 of file "/tmp/testing/counters"
This command reads the current contents of the file, adds 1 to the second item on the first line, and stores the modified value back into the file.
The following example shows how you could use a file expression to read an entire file, and then process it one line at a time:
put file "/Users/bob/Desktop/TestRead" into MyFileVar
repeat with each line output of MyFileVar
log output
end repeat
Although this example merely logs each line after it is read, you could easily add code to perform additional actions with the content of each line, which here is contained in the variable output
.
When reading a file as a container if the file does not exist or cannot be accessed, the value of the result
is set to an error message. The value of the file expression is treated as empty in this case, as shown in the following example:
put file "/nonExistent/File" into contents
put the result --> File not found: /nonExistent/File
put contents is empty --> True
If a command attempts to write to a file and fails for some reason (such as insufficient privileges for writing to the file), the result
is set to an error message.
Treating a file as a container is easy and works well for many situations. Occasionally, it might not be the most efficient approach to use if your script needs to do a significant number of read and write operations in a file. In these cases, you might prefer to use the commands described below in Commands and Functions for Working with Files.
Configuring File Behavior
When accessing a file as a container, text is interpreted during both reading and writing according to the setting of the defaultStringEncoding
global property. By default, SenseTalk uses UTF-8, a common 8-bit system for encoding Unicode characters. To read or write a file as binary data instead of as text, specify as data
:
put file "/tmp/datafile"as dataintomyData
putcontentsas dataintofile "/tmp/binaryFile"
When your SenseTalk command creates a new file, you can control the access permissions for the file as well as access to any folder created in the directory structure. See The Umask
global property for complete details about reading or setting these properties.
You can use The StrictFiles
global property to control the behavior when reading a nonexistent file as a container. The default is false, which means the nonexistent files are treated as empty. Set this property to true if you want to throw an exception if the file doesn't exist.
Commands and Functions for Working with Files
The file input and output commands (open file
, close file
, read from file
, seek in file
, and write to file
) are for creating and accessing text or binary files on your system. Use them to read and write data that is stored in the file system.
In addition to using these commands, you can access a file directly as a container within your script, as described above. Accessing a file as a container provides the simplest means of reading or manipulating its contents, but provides less control and is somewhat less efficient when performing multiple operations on the same file than the commands described here.
Open File
Command
Behavior: Opens or creates a file for reading or writing or both. The open file
command must be used to open a file before anything can be read from or written to that file with the read
or write
commands. When you are finished with a file, you should close it by using either the close file
or close all
command.
Parameters: The name of a file to open or create.
Syntax:
open file fileName { for [reading | writing | readwrite | appending | updating] }
If the fileName expression does not yield the name of an existing file, the file will be created. If fileName is not an absolute path, it is assumed to be relative to the current working folder.
Example:
open file myFile
Example:
Open file "/etc/passwd" for reading
Example:
put "/Users/bkwins/Desktop/testfolder1/testfile.txt" into MyFileVar
open file MyFileVar for appending
When you open a file, you can optionally specify the manner in which the file will be accessed. You can open files for reading only, for writing only, or for both reading and writing. The default mode is updating
if you don't specify the manner of access.
The following table lists the modes and summarizes the differences between them:
Mode | Can Read | Write / Create | Starts At | Existing File |
---|---|---|---|---|
Reading | yes | no | beginning | unchanged |
Writing | no | yes | beginning | replaces existing file |
ReadWrite | yes | yes | beginning | truncates after highest write |
Appending | yes | yes | end of file | never truncated; may grow |
Updating | yes | yes | beginning | never truncated; may grow |
All of the modes except for reading
will create the file (including the full path to it) if it doesn’t already exist.
The readwrite
, appending
, and updating
modes all open the file for both reading and writing. However, a file opened in readwrite
mode will be truncated following the last (highest) character position in the file that is written to. If nothing is written to the file, it will be left unchanged.
If you want to open a file (but only if it already exists), use file fileName exists or there is a file fileName to check for the file's existence, as shown in this example:
Example:
if there is a file myFile then
open file myFile for updating
else
answer "File " & myFile & " doesn't exist!"
exit all
end if
Related:
Close File
,Close All
: Use these commands to close open files.OpenFiles
: Use this function to get a list of all files that are currently open.
Close File
, Close All Files
Commands
Behavior: The close file
command closes an open file that was opened with the open file
command. The close all files
command closes all open files that were opened with the open file
command. Use the close file
command when your script has finished accessing a file, or use the close all files
command to close all of the currently open files.
SenseTalk automatically closes all open files whenever it stops executing your scripts, but it is a good practice for your script to close files when it is done working with them.
Parameters: For close file
, the name of a file to close is required. The close all files
command does not take a parameter.
Syntax:
close file fileName
close all { files }
The fileName should be an expression that gives the name of the file to be closed. The file name should be either the full path name of the file, or it should be given relative to the current working folder (as returned by the folder
).
Example:
close file "/etc/passwd"
Example:
close all files -- closes all open files that were opened with the open files command
The close all files
command closes all currently open files, regardless of which script or handler opened the file. This behavior could be potentially problematic if files have been opened by other scripts and are still in use. You can use the openFiles()
function to get a list of all open files.
Related:
Open File
: Use this command to open a specified file.OpenFiles
: Use this function to get a list of all files that are currently open.
Current Position in File
Function
Behavior: Obtains the position of the next byte within an open file that will be read or written. Position 1 represents the beginning of the file.
Syntax:
{the} {current} [position | location | offset] in file filename
Example:
get the current position in file myFile
Read from File
Command
Behavior: Use the read from file
command to read data from a file. Note that the file must first be opened with the open file
command. Data is read into the variable it
or into a destination container if specified (using an into
clause).
The read from file
command can read a specified number of characters, words, items, lines, or bytes; can read until a specified delimiter is found; or can read a list of one of several different types of numeric values. Reading begins at the current position, or at a starting position specified by using an at
clause.
When there is no more data to read, the destination container will be empty. Any time less data is read than was requested, the result
function will contain a value giving the reason (such as time out
, or eof
if the end of file is reached).
Parameters: The name of a file that was previously opened with an open file
command. The file must have been opened in a mode that permits reading (that is, not in writing
mode, which permits only writing).
Syntax:
read Options
Source Option: Required.
from file fileName
Quantity Options: Optional. Only one can be used at a time.
until [ {the} eof | {the} end {of {the} file} | terminator ]
for quantity {dataType}
[a | an | quantity] dataType
{for} {a | an} http {message | request | response}
{for} {a | an} [xmlrpc | xml-rpc] {message | request | response}
Other Options: Optional. More than one can be used at a time.
at startPos
[ in | [timeout | time out] {after | in} ] timeoutDuration
into container
Use at startpos to specify the byte position within the file where the read from file
command starts reading. If the startpos value is a negative number, it specifies the number of bytes back from the end of the file where reading begins. If you don't specify a startpos value, the first character or byte to be read is the one at the current position in the file, as determined by the most recent prior read
, write
, or seek
command in that file.
If into container is specified, the data that is read is put into the given container. If a container is not specified, the data is read into the special it
variable.
If until terminator (or one of the other variations) is specified, all of the characters from the starting position until the next occurrence of the specified character or string will be read. This option is useful for reading one line at a time from the source (by using return
as the terminating character), or to read until some other delimiting character (such as a tab
) is found. The terminator can be more than one character in length, and will be returned as part of the value that was read. Specifying until eof
or until end
will read to the end of the file.
If for quantity dataType is used, the number of characters or other data elements specified by quantity are read from the file. If dataType is a text chunk type (i.e., characters
, words
, items
, or lines
), text is read until the requested amount is available. The final delimiter (if any) is not included with the text that is read. If no dataType is given, bytes
are assumed (and the word for
is required in this case).
If you specify a numeric data type instead of a text chunk type, the value stored into it
or container by the read will be a list of the data values that were read. The following numeric data types can be used:
Data Type | Value |
---|---|
int1 or 8-bit integer | an 8-bit (or 1 byte) signed integer |
uint1 or unsigned 8-bit integer | an 8-bit (or 1 byte) unsigned integer |
int2 or 16-bit integer or short integer | a 16-bit (or 2 byte) signed integer |
uint2 or unsigned 16-bit integer | a 16-bit (or 2 byte) unsigned integer |
int4 or 32-bit integer or integer | a 32-bit (or 4 byte) signed integer |
uint4 or unsigned 32-bit integer | a 32-bit (or 4 byte) unsigned integer |
int8 or 64-bit integer | a 64-bit (or 8 byte) signed integer |
uint8 or unsigned 64-bit integer | a 64-bit (or 8 byte) unsigned integer |
real4 or 32-bit real or float | a 32-bit (single-precision) floating-point number |
real8 or 64-bit real or double | a 64-bit (double-precision) floating-point number |
Example:
read from file myFile for 20 -- Reads the next 20 bytes into it
Example:
read from file myFile into myFileVar until return
-- Reads the first line and puts it into a variable
Example:
read 100 characters from file xyz into input -- Reads the next 100 chars into input
Example:
read into inQueue 5 items from file dataFile at 100
-- Starting at position 100 (100th byte), reads 5 text items
-- and puts them in the variable inQueue
Here is an example showing one way to read and process an entire file one line at a time:
Example:
open file "/tmp/abcd"
repeat forever
read from file "/tmp/abcd" until return -- reads one line
if it is empty then exit repeat -- we've reached the end of the file
put it -- or do other processing with 'it' here
end repeat
close file"/tmp/abcd"
Related:
Open File
Command: Use this command to open a specified file.Write to File
Command: Use this command to write text or data to an open file.Close File
andClose All
Commands : Use these commands to close open files.Read from Socket
,Read from Process
,Read from Input
Commands: These related commands enable reading from sources other than a file.
Seek in File
Command
Behavior: Sets the position within a file where the next read
or write
command will occur. Use the seek
command to set the current position in a file before performing a read
or write
in that file. Although the read
and write
commands both provide at startPos options to specify the starting position for that operation, the seek
command provides additional flexibility because the position in the file can be specified relative to the current location as well as from the beginning or end of the file.
Parameters: The name of a file that was previously opened with an open file
command.
Syntax:
seek in file fileName [at | to] position { from | before | after {the} [start | beginning | current position | end] }
The position is a numeric expression that specifies the location to seek to in the file. If you don't use one of the from
options to specify the origin of the seek, then a positive position indicates the number of bytes from the beginning of the file, and a negative position indicates the number of bytes back from the end of the file. Instead of a number or numeric expression, position can also be the end
, which means the same as 0 from the end
.
You can include a from
option to specify whether position is relative to the beginning or end of the file or from the current position. You can include before
or after
to specify the position to search.
Example:
seek in file myFile to 10 from the current position
Example:
seek in file "/Users/bkwins/Documents/newText" to the end
Example:
seek in file myFile to 8 bytes before the current position
Related:
Read from File
: Use read from file to read text or data from an open file.Write to File
: Use this command to write text or data to an open file.
Write to File
Command
Behavior: Writes data into a file. Use the write
command to store data in a file on disk. The data can then be read from the file again at a later time by your scripts, or by another application entirely.
Parameters: The name of a file that was previously opened with an open file
command. The file must have been opened in a mode that permits writing (that is, not in reading
mode, which permits only reading).
Syntax:
write data {as dataType} to file fileName {at [startpos | end | eof]}
The data can be any valid SenseTalk expression. If dataType is not specified, the value of the data expression is treated as a string of characters, which is written out to the specified file.
If at startpos is specified, writing to the file begins at that byte position within the file. If the startpos value is negative, it specifies the number of bytes back from the end of the file where writing begins. Using the at end
or at eof
option tells SenseTalk to write the data at the end of the file, following any other text already in the file. If no location is specified, data is written beginning at the current position in the file, as determined by the most recent prior read
, write
, or seek
command in that file.
If as dataType is specified, the data is converted to that binary format before being written. In this case, data can be a list of numeric values, which are all converted to the same data type. See the read from file
command for a list of the valid data types.
Example:
write line 1 of accounts & return to file myFile
Example:
write highScore & tab to file "~/.gamescores" at eof
Example:
write numberList as 16-bit integers to file bData
Example:
put "/Users/bob/Desktop/TestRead" into MyFileVar // creates a variable with a path to a file
open file MyFileVar // opens the file
put "GIO NOW" into MyWrite // puts a text string into a variable
write return to file MyFileVar at eof // adds a return character to the end of the file to ensure that new writes begin on a new line
write MyWrite to file MyFileVar // writes the text from the variable into the file
close file MyFileVar // closes the file
Writing into a file at a position that already contains data overwrites the existing data. To insert text into the middle of an existing file, you must read all of the text in the file from that point to the end and store it in a container. Then the text to be inserted can be written out, followed by the stored text.
If an existing file is opened in readwrite
or appending
mode, writing to the file causes data to be dropped from the file beyond the highest position that gets written to in the file. To avoid this file truncation, open the file in updating
mode. See the open file
command for more information about these modes.
When you are finished accessing a file, it should be closed with the close file
command to ensure that all of the data written out is saved properly to the disk.
Related:
Open File
: Use this command to open a specified file.Read From File
: Use read from file to read text or data from an open file.Close File
,Close All
: Use these commands to close open files.The DefaultStringEncoding
: This global property specifies how text strings are encoded when they are read from or written to a file.
OpenFiles
Function
Behavior: Returns a list of the files that are currently open as a result of the open file
command.
Parameters: None.
Syntax:
the openFiles
openFiles()
Example:
log the openFiles
Example:
open file "/Users/bkwins/Documents/newText"
put openFiles() into myVar
log myVar
You could use openFiles()
to perform actions on only certain open files. For instance, the following example shows how you might use the information returned by the funtion to close all open files whose names end in .dat.
Example:
repeat with each item of the openFiles
if it ends with ".dat" then close file it
end repeat
Related:
Open File
: Use this command to open a specified file.Close File
,Close All
: Use these commands to close open files.
Commands and Functions for Working with File Systems
Several commands and functions provide access to the file system on the machine where the script is running (or a locally mounted file system), enabling your script to create, move, copy, rename, and delete files and folders, and to obtain information about the files and folders in the system.
Create File
, Create Folder
, Create Link
Commands
Behavior: Creates a new file or folder in the file system, or a symbolic link to an existing file or folder. Use the create folder
command to create a new folder on the disk. Use the create file
command to create an empty file. Use create link
to create a link (sometimes called an alias or a symbolic link) that looks like an independent file, but is actually a reference to a different file on the disk.
You can also create a file by using the open file
command for a file that doesn't exist, or by using the put
command to put something into a file that doesn't exist. Both methods create the file as well as any specified directory structure.
Parameters: For create file
and create folder
, the name of the file or folder to create is required. For create link, the name of the link and the name of the file or folder to link to are required.
Syntax:
create {a} {new} [file | folder | directory] fileOrFolderName {with properties}
create {a} {new} link linkName to [file | folder | directory] fileOrFolderName
The fileOrFolderName expression must yield either an absolute path name or a path name relative to the current folder. The file, folder, or link being created must not already exist. If its parent folder does not exist, it will also be created.
If the with properties option is used, properties should be a property list specifying initial values for any of the following properties: ownerName, groupName, permissions, creationDate, modificationDate, and for files: typeCode, creatorCode, fileExtensionHidden, appendOnly, or locked. See Accessing File Properties for more information about setting these properties.
Example:
create file "/tmp/myWorkArea/testData"
Example:
create a new folder "/tmp/myWorkArea"
Example:
create folder "/tmp/myWorkArea/subdir" with {groupName:"admin", permissions:"rwxrwxr-x"}
Example:
create link "tasty" to file "juicy"
Set the throwExceptionResults
global property to false to prevent this command from throwing exceptions and to allow its error to become available through the result() function.
Delete File
, Delete Folder
Commands
Behavior: Permanently removes a file or folder from the disk. Use the delete
command to destroy a file, or to destroy a folder including all of its contents. This command is permanent and irreversible—use with caution.
Parameters: The name of a file or folder to delete.
Syntax:
delete [file | folder | directory] fileOrFolderName
The fileOrFolderName expression must yield the name of an existing file or folder. Deleting a folder deletes all of the files and folders within it as well.
Example:
delete file "testData27"
Example:
delete folder "/tmp/myWorkArea"
Set the throwExceptionResults
global property to false to prevent this command from throwing exceptions and to allow its error to become available through the result() function.
Rename File
, Rename Folder
Commands
Behavior: Use the rename
command to change the name of a file or folder.
Parameters: The name of the file whose name you want to change, and the new name for the file are both required.
Syntax:
rename [file | folder | directory] originalName as newName
The originalName expression must yield the name of an existing file or folder. If newName is not a full path name, it is taken to be relative to the folder where the source file or folder is located.
Example:
rename folder "/tmp/myWorkArea" as "oldWorkArea"
Example:
rename file sourceFile as sourceFile && "backup"
Set the throwExceptionResults
global property to false to prevent this command from throwing exceptions and to allow its error to become available through the result() function.
Copy File
, Copy Folder
Commands
Behavior: Makes a duplicate copy of an existing file or folder. Use the copy
command any time you want to make a complete copy of a single file or of a folder and all of its contents.
There are three forms of the copy
command: copy ... into ...
, copy ... as ...
, and copy ... to ...
. The first form, using the preposition into
, makes a copy of the source file or folder with the same name as the original in a different destination folder. If the destination folder does not exist, it will be created.
The second form of copy
, using the preposition as
, lets you assign a different name to the copy. The copy can be created in the same folder as the source, or in a different folder. The final form of copy
, using the preposition to
, behaves just like copy ... into ...
if the destination is an existing folder, otherwise it behaves like copy ... as ...
.
Parameters: The name of a file to copy is required. Either a new name or new destination for the copy is also required.
Syntax:
copy [file | folder | directory] sourceName [into | to] {folder | directory} destinationFolder
copy [file | folder | directory] sourceName [as | to] destinationName
The sourceName expression must yield the name of an existing file or folder. If sourceName is not an absolute path, it is assumed to be relative to the current working folder. If the destinationFolder or destinationName is not an absolute path, it is assumed to be relative to the parent directory of the source file or folder.
Example:
copy file results into folder resultsArchiveFolder
Example:
copy file "/tmp/testFile" as "/tmp/testFileCopy"
Example:
copy folder planFldr to "~/Documents"
Set the throwExceptionResults
global property to false to prevent this command from throwing exceptions and to allow its error to become available through the result() function.
Move File
, Move Folder
Commands
Behaviors: Moves a file or folder to a new location in the file system. Use the move ... into ...
command to move a file or folder into a different parent folder without changing its name. The move ... to ...
command (similar to the copy ... to ...
command) assigns a new name to the file or folder being moved unless the destination is an existing folder, in which case the source file or folder is moved into the destination folder without changing its name.
Parameters: The name of a file or folder to move and the name of the destination are both required.
Syntax:
move [file | folder | directory] sourceName [into | to] {folder | directory} destinationFolder
If sourceName is not an absolute path, it is assumed to be relative to the current working folder. If the destinationFolder is not an absolute path, it is taken to be relative to the parent folder of the source file or folder. If the destinationFolder does not exist, it will be created.
Example:
move file "/tmp/testFile" into folder "archives"
Set the throwExceptionResults
global property to false to prevent this command from throwing exceptions and to allow its error to become available through the result() function.
Files
Function
Behavior: Returns a list of all of the files in the current working folder, or in a specified folder. Use the files
function to find out what files exist in a given folder in the file system.
Parameters: If the files
function is called without any parameter (or with an empty parameter), it returns a list of files in the current working folder. If a parameter is given, it should be the name of an existing folder, and the function returns the list of files in that folder.
Syntax:
the files {of folder}
files( {folder} )
Returns: A list containing one item for each of the non-folder entries in the specified folder (or in the current working folder if no folder is specified). Each item in the returned list is a fileDescription object (a property list with objectType
set to "fileDescription"). The asText property of each fileDescription is set to the local name of the file, so displaying it simply shows the file’s name.
Example:
put files("/Users/bkwins/Desktop")
Example:
put the files of "/Users/bkwins/Desktop"
You can easily iterate over all of the files in the list returned by the files
function to work with each file in turn. The following example shows such a use case where you might want to back up only certain file types.
Example:
// backup all ".st" files into backupFolder
repeat with each item of the files -- looks at all files in working folder
if it ends with ".st" then copy file it into backupFolder
else put "Not backed up: " & it & " of size " & it.size
end repeat
Each fileDescription object also holds many additional items of information. In particular, the "long name" property contains the full path name of the file. Other properties include the parent folder where the file is located, and such information as the file size, owner, and permissions. Use the archive()
function (or delete the object’s asText property before displaying it) to find out exactly what information is available.
SenseTalk commands and functions that work with files, such as the copy file
and rename
commands and the diskSpace()
function, recognize fileDescription objects that are used in place of file names, and will use the long name to identify the actual file. In this way, fileDescription objects can serve as file identifiers that can be stored in variables, passed as parameters, and so forth.
Related:
Folders
Function
Behavior: Returns a list of all the subfolders in the current working folder, or in a specified folder. Use the folders
function to find out what folders exist within a given folder in the file system.
Parameters: If the folders
function is called without any parameter, it returns a list of folders in the current working folder. If a parameter is given, it should be the name of an existing folder, and the function returns the list of subfolders within that folder.
Syntax:
the folders {of parentFolder}
folders( {parentFolder} )
The parentFolder expression must yield the name of an existing folder.
Returns: A list containing one item for each of the subfolder entries in parentFolder (or in the current working folder, if parentFolder is not specified).
Example:
log folders() // logs all folders in the current working directory
Example:
put the folders of "/Users/bkwins/Desktop/" into myFolderListVar
// puts a list of folders on the Desktop into a variable
You can easily iterate over all of the folders in the list returned by the folders
function and work with each folder in turn. For instance, you could use the code in the following example to show all the individual files within each subfolder of a folder.
Example:
// show the files in each subfolder of the current folder
repeat with each item of the folders
put "Folder " & it & return & the files of it
end repeat
Each item in the returned list is a fileDescription object (property list) which shows the local name of the folder when displayed, but also contains many additional items of information about the folder, such as its modification date and permissions settings. See the files
function, above, or the fileDescription
function for more information about fileDescription objects.
Related:
FilesAndFolders
Function
Behavior: Returns a list of all files and subfolders in the current working folder, or in a specified folder. Use the filesAndFolders
function to find out what files and folders exist within a given folder in the file system.
Parameters: If the filesAndFolders
function is called without any parameter, it returns a list of files and folders in the current working folder. If a parameter is given, it should be the name of an existing folder, and the function returns the list of files and subfolders within that folder.
Syntax:
the filesAndFolders {of parentFolder}
filesAndFolders( {parentFolder} )
The parentFolder expression must yield the name of an existing folder.
Returns: A list containing one item for each of the file and subfolder entries in parentFolder (or in the current working folder if parentFolder is not specified).
Example:
log filesandfolders() // logs all files and folders in the current working directory
Example:
put the filesandfolders of "/Users/bkwins/Desktop/" into folderContents
// puts a list of files and folders on the Desktop into a variable
You can easily iterate over all of the items in the list returned by the function to work with each file or folder in turn. The following example shows how you could process each item, treating files and folders differently.
Example:
// show the files in the current folder and its subfolders
repeat with each item of the filesAndFolders
if it is a folder then
put "Folder: " & it & " -- " & the files of it
else
put "File: " & it
end if
end repeat
Each item in the returned list is a fileDescription object (property list) that shows the local name of the file or folder when displayed, but also contains many additional items of information about that item, such as its modification date and permissions settings. See the files
function, above, or the fileDescription function for more information about fileDescription objects.
Related:
Zip File
, Zip Folder
Commands
Behavior: Makes a compressed archive (a .zip file) of an existing file or folder. Use the zip
command any time you want to make an archived copy of a single file, or of a folder and all of its contents.
There are several forms of the zip
command. The simplest, "zip file filename", will create a zipped file named filename.zip in the same folder where the source file was located. To give a different output file name, include "as zipFilename" in the command. To put the output in a different location, include the "into folderName" clause. If the destination folder does not exist, it will be created.
Additional options can also be specified by including "with optionPropertyList" at the end of the command. Possible options include:
- password: A password string. If included, the resulting zip archive will be encrypted and can only be unzipped by supplying the password again.
- encryptKeyLength: Must be 128, 192, or 256 (default 128). The key length to use for encryption.
- compressionLevel: Integer (default 6) to specify the amount of compression to use, from 0 (no compression) to 9 (maximum compression)
- includeSubfolders: Boolean (default True/Yes). Whether to include subfolders in the archive, or only the files at the top level of the folder.
- filesToInclude: A wildcard pattern string to specify which files within the folder to include in the archive (
"*"
= all files (the default),"*.txt"
= all text files, etc.).FilesToInclude
can also be given as a list of wildcard strings to include (e.g.,filesToInclude:["*.txt", "*.script"]
).
Parameters: The name of a file or folder to be zipped is required. Other parameters are optional.
Syntax:
zip file sourceFileName {[as | to] zippedFileName} {[into | in] [folder | directory] destinationFolder} {with optionPropertyList}zip [folder | directory] sourceFolderName {[as | to] zippedFileName} {[into | in] [folder | directory] destinationFolder} {with optionPropertyList}
The sourceFileName or sourceFolderName expression must yield the name of an existing file or folder. If it is not an absolute path, it is assumed to be relative to the current working folder. If the destinationFolder or zippedFileName is not an absolute path, it is assumed to be relative to the parent directory of the source file or folder.
Unzip File
Command
Behavior: Uncompresses and extracts the contents of a .zip archive file. Use the unzip
command any time you want to unzip a file and retrieve its contents.
There are several forms of the unzip
command. The simplest, "unzip file filename", extracts the contents into the same folder where the source .zip file was located. To give a different output file name (for .zip archives of a single file), include "as unzippedFileName" in the command. To put the output in a different location, include the "into destinationFolder" clause. If the destination folder does not exist, it will be created.
Parameters: The name of a .zip file is required. Additional options can be specified by including "with optionPropertyList" at the end of the command. Possible options include:
- password: The password string to use when unzipping an encrypted archive.
- overwriteExistingFiles: Boolean (default True/Yes). Whether extracted files should replace existing files with the same name.
- newerFilesOnly: Boolean (default False/No). If set to true, any existing files will be replaced by files extracted from the archive only if the archive contains newer versions of those files.
Syntax:
unzip file zipFileName {[as | to] unzippedFileName} {[into | in] [folder | directory] destinationFolder} {with optionPropertyList}
The zipFileName expression must yield the name of an existing .zip file. If it is not an absolute path, it is assumed to be relative to the current working folder. If the destinationFolder or unzippedFileName is not an absolute path, it is assumed to be relative to the parent directory of the source .zip file.
AvailableStringEncodings
Function
Behavior: Returns a list of the names of all the available string encoding formats. In some cases there might be more than one name for the same encoding. Use the availableStringEncodings
function to learn the names of the encodings that are available to use when setting the defaultStringEncoding
global property.
Syntax:
the availableStringEncodings
availableStringEncodings()
Example:
put the availableStringEncodings
Functions for Working with CSV Formats
During your SenseTalk scripting you might need to do some formatting of CSV data. SenseTalk includes the CSVFormat
function and the CSVValue
function to assist you with CSV formats.
CSVFormat
Function
Behavior: This function accepts a value, which is either a list of lists or a list of property lists, and returns a text representation of that list in CSV format.
Parameters: In addition to a list of lists or property lists, the CSVFormat
function accepts the following options:
- delimiter: The
delimiter
option value represents a character to be used between the fields on each line. The default value is a comma. - columnNames: A list of the column names.
Syntax:
CSVFormat( [listOfLists | listOfPropertyLists] {, options} )
{the} CSVFormat of [listOfLists | listOfPropertyLists]
Example:
put ["id","LName","FName","Address","City","State","Zip"] into colNames // Adds header names to a list
put CSVFormat([colNames,customer1,customer2,customer3])
// Outputs the header names that were added to the colNames list and the current values contained in customer1, customer2, and customer3, all in CSV format:
// id,LName,FName,Address,City,State,Zip
// 1,Smith,Joe,123 Happy Place,Boulder,CO,80303
// 2,Jones,Mary,456 Happy Place,Boulder,CO,80303
// 3,Brown,James,456 Happy Place,Boulder,CO,80303
CSVValue
Function
Behavior: This function accepts text in CSV format and converts it into either a list of property lists or a list of lists.
Parameters: In addition to the CSVstringToEvaluate, the CSVValue
function accepts the following options:
- delimiter: This value represents a character to be used between the fields on each line. The default value is a comma.
- asLists: Setting this value to
Yes
tells theCSVValue
function to create a list of lists. The default value isNo
, which results in the creation of a list of property lists. - columnNames: The
columnNames
option value represents a list of names for the columns. Specify this option when there is no header row. TheCSVValue
function ignores this option if theasLists
parameter is set. - trimValues: Set this value to
Yes
to trim any spaces before and after each value. The default value isNo
. - ignoreComments: Set this value to
Yes
to recognize and ignore comments beginning with the#
character. The default value isNo
. - allowEscapes: Set this value to
Yes
to allow backslashes in values to escape the character that follows the backslash. The default value isNo
.
Syntax:
CSVValue( CSVstringToEvaluate {, options} )
{the} CSVValue of CSVstringToEvaluate
Example:
put CSVValue of file ResourcePath("TestCustomerList_CSV.csv") into Customers
// Reads a list of customers from the TestCustomerList_CSV.csv file and places them in the Customers list
repeat for each item of Customers
put it // Displays each item contained in the Customers list
end repeat
// Outputs the following items from the Customers list (these contents are the assumed TestCustomerList_CSV.csv file contents for this example) :
// (City:"New York", @"Company Name":"ABC", Country:"United States", @"Customer ID":"2", @"Postal Code":"12345", State:"New York")
// (City:"Seattle", @"Company Name":"XYZ", Country:"United States", @"Customer ID":"3", @"Postal Code":"12345", State:"Washington")
Related:
Related Global Properties
SenseTalk includes a few global properties that affect work with files and file system objects.
To provide stricter control over the use of files at runtime, the strictFiles
global property can be used to determine whether an attempt to read a nonexistent file returns an empty value (the default) or throws an exception.
You can use the defaultStringEncoding
global property to specify how text strings are encoded when they are read from or written to a file, socket, or URL. The default method is UTF8, but many other encoding methods can be used.
You can use the umask
global property to control the access permissions for any file or folder created by SenseTalk, either directly or indirectly.