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"