Python API

FileSystem

Files and filesystems library for Robot Framework

class RPA.FileSystem.Directory(path: str, name: str)

Bases: NamedTuple

Robot Framework -friendly container for directories.

count(value, /)

Return number of occurrences of value.

classmethod from_path(path)

Create a directory object from pathlib.Path or a path string.

index(value, start=0, stop=9223372036854775807, /)

Return first index of value.

Raises ValueError if the value is not present.

name: str

Alias for field number 1

path: str

Alias for field number 0

class RPA.FileSystem.File(path: str, name: str, size: int, mtime: float)

Bases: NamedTuple

Robot Framework -friendly container for files.

count(value, /)

Return number of occurrences of value.

classmethod from_path(path)

Create a File object from pathlib.Path or a path string.

index(value, start=0, stop=9223372036854775807, /)

Return first index of value.

Raises ValueError if the value is not present.

mtime: float

Alias for field number 3

name: str

Alias for field number 1

path: str

Alias for field number 0

size: int

Alias for field number 2

class RPA.FileSystem.FileSystem

Bases: object

The FileSystem library can be used to interact with files and directories on the local computer. It can inspect and list files, remove and create them, read contents from files, and write data out.

It shadows the built-in OperatingSystem library but contains keywords which are more RPA-oriented.

Examples

Robot Framework

The library allows, for instance, iterating over files and inspecting them.

*** Settings ***
Library    RPA.FileSystem

*** Keywords ***
Delete large files
    ${files}=    List files in directory    archive/orders/
    FOR    ${file}  IN  @{FILES}
        Run keyword if    ${file.size} > 10**8    Remove file    ${file}
    END

Read process output
    Start external program
    Wait until modified    process.log
    ${output}=  Read file  process.log
    [Return]    ${output}

Python

The library can also be used inside Python.

from RPA.FileSystem import FileSystem

def move_to_archive():
    lib = FileSystem()

    matches = lib.find_files("**/*.xlsx")
    if matches:
        lib.create_directory("archive")
        lib.move_files(matches, "archive")
PATH_TYPE

alias of Union[str, Path]

ROBOT_LIBRARY_DOC_FORMAT = 'REST'
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
absolute_path(path: Union[str, Path]) str

Returns the absolute path to a file, and resolves symlinks.

Parameters

path – path that will be resolved

Returns

absolute path to file as a string

append_to_binary_file(path: Union[str, Path], content: Any) None

Appends binary content to the given file.

See `Create Binary File` for usage example.

Parameters
  • path – path to file to append to

  • content – content to append

append_to_file(path: Union[str, Path], content: str, encoding: str = 'utf-8') None

Appends text to the given file.

See `Create File` for usage example.

Parameters
  • path – path to file to append to

  • content – content to append

  • encoding – character encoding of appended content

change_file_extension(path: Union[str, Path], extension: str) None

Replaces file extension for file at given path. the file extension can be removed by passing an empty string.

Parameters
  • path – path to file to rename

  • extension – new extension, e.g. .xlsx

Example:

*** Tasks ***
Change a file extension
    Change file extension
    ...    devdata/work-items-in/default/orders.xls
    ...    .xlsx
copy_directory(source: Union[str, Path], destination: Union[str, Path]) None

Copy directory from source path to destination path.

Parameters
  • source – path to source directory

  • destination – path to copy destination

Example:

*** Tasks ***
Copy a directory
    Copy directory    output    temp
copy_file(source: Union[str, Path], destination: Union[str, Path]) None

Copy a file from source path to destination path.

See `Is Directory Empty` for usage example.

Parameters
  • source – path to source file

  • destination – path to copy destination

copy_files(sources: List[Union[str, Path]], destination: Union[str, Path]) None

Copy multiple files to destination folder.

Parameters
  • sources – list of source files

  • destination – path to destination folder

Example:

*** Tasks ***
Copy some files
    ${files}=    Find files    devdata/*.json
    Copy files    ${files}    output
create_binary_file(path: Union[str, Path], content: Optional[Any] = None, overwrite: bool = False) None

Creates a new binary file, and writes content if any is given.

Parameters
  • path – path to file to write

  • content – content to write to file (optional)

  • overwrite – replace destination file if it already exists

Example:

*** Tasks ***
Create a new file
    ${content}=    Get
    ...    url=https://file-examples.com/storage/fe88505b6162b2538a045ce/2017/10/file_example_JPG_100kB.jpg
    Create binary file    output/sample.jpg    content=${content.content}    overwrite=${True}
create_directory(path: Union[str, Path], parents: bool = False, exist_ok: bool = True) None

Creates a directory and (optionally) non-existing parent directories.

Parameters
  • path – path to new directory

  • parents – create missing parent directories (defaults to False)

  • exist_ok – continue without errors if directory already exists (defaults to True)

Example:

*** Tasks ***
Create new path
    Create directory    output/my/new/path    parents=${True}
create_file(path: Union[str, Path], content: Optional[str] = None, encoding: str = 'utf-8', overwrite: bool = False) None

Creates a new text file, and writes content if any is given.

Parameters
  • path – path to file to write

  • content – content to write to file (optional)

  • encoding – character encoding of written content (default utf-8)

  • overwrite – replace destination file if it already exists (default False)

Example:

*** Tasks ***
Create a new file
    ${content}=    Get    url=https://www.example.com
    Create file    output/newfile.html    content=${content.text}
    ...    overwrite=${True}
does_directory_exist(path: Union[str, Path]) bool

Returns True if the given directory exists, False if not.

See `Does Directory Not Exist` for usage example.

Parameters

path – path to inspected directory

Returns

true or false if the directory exists

does_directory_not_exist(path: Union[str, Path]) bool

Returns True if the directory does not exist, False if it does.

Parameters

path – path to inspected directory

Returns

true or false if the directory does not exists

Example:

*** Tasks  ***
Check for directory
    ${directory_exists}=    Does directory not exist    output
    IF    ${directory_exists}    Create directory    output
does_file_exist(path: Union[str, Path]) bool

Returns True if the given file exists, False if not.

Parameters

path – path to inspected file

Returns

true or false if file exists

Example:

*** Tasks  ***
Check for file
    ${log_exists}=    Does file exist    output/log.html
    IF    ${log_exists}
        ${file}=    Find files    output/log.html
        Open user browser    ${file}[0]
    END
does_file_not_exist(path: Union[str, Path]) bool

Returns True if the file does not exist, False if it does.

See `Does File Exist` for usage example.

Parameters

path – path to inspected file

Returns

true or false if the files does not exist

empty_directory(path: Union[str, Path]) None

Removes all the files in the given directory.

Parameters

path – directory to remove files from

Example:

*** Tasks ***
Empty out directory
    Empty directory    output
find_files(pattern: Union[str, Path], include_dirs: bool = True, include_files: bool = True) list

Find files recursively according to a pattern.

Parameters
  • pattern – search path in glob format pattern, e.g. .xls or */orders.txt

  • include_dirs – include directories in results (defaults to True)

  • include_files – include files in results (defaults to True)

Returns

list of paths that match the pattern

Example:

*** Tasks  ***
Finding files recursively
    ${files}=    Find files    **/*.log
    FOR    ${file}    IN    @{files}
        Read file    ${file}
    END
get_file_creation_date(path: Union[str, Path]) float

Returns the creation time in seconds. Note: Linux sets this whenever file metadata changes

Parameters

path – path to file to inspect

Returns

creation time in seconds as a float

get_file_extension(path: Union[str, Path]) str

Returns the suffix for the file.

Parameters

path – path to file

Returns

file suffix as a string

get_file_modified_date(path: Union[str, Path]) float

Returns the modified time in seconds.

Parameters

path – path to file to inspect

Returns

modified time in seconds as a float

get_file_name(path: Union[str, Path]) str

Returns only the full file name portion of a path.

Parameters

path – path to file

Returns

filename portion of a path as a string

get_file_owner(path: Union[str, Path]) str

Return the name of the user who owns the file.

Parameters

path – path to file to inspect

Returns

file owner as a string

get_file_size(path: Union[str, Path]) int

Returns the file size in bytes.

Parameters

path – path to file to inspect

Returns

file size in bytes as an int

get_file_stem(path: Union[str, Path]) str

Returns the name of the file without its extension.

Parameters

path – path to file

Returns

filename without its suffix as a string

is_directory_empty(path: Optional[Union[str, Path]] = None) bool

Returns True if the given directory has no files or subdirectories.

Parameters

path – path to inspected directory

Returns

true or false if the directory is empty

Example:

*** Tasks  ***
Check for empty directory
    ${directory_empty}=    Is directory empty    output
    IF    ${directory_empty}
        Copy file    ${source}    output/new_file.txt
    END
is_directory_not_empty(path: Optional[Union[str, Path]] = None) bool

Returns True if the given directory has any files or subdirectories.

See `Is Directory Empty` for usage example.

Parameters

path – path to inspected directory

Returns

true or false if the directory is not empty

is_file_empty(path: Union[str, Path]) bool

Returns True if the given file has no content, i.e. has zero size.

Parameters

path – path to inspected file

Returns

true or false if the file is empty

is_file_not_empty(path: Union[str, Path]) bool

Returns True if the given file has content, i.e. larger than zero size.

Parameters

path – path to inspected file

Returns

true or false if the file is not empty

Example:

*** Tasks ***
Check for empty file
    ${file_empty}=    Is file not empty    output/log.html
    IF    ${file_empty}
        Copy file    output/log.html    ${alt_dir}
    END
join_path(*parts: Union[str, Path]) str

Joins multiple parts of a path together.

Parameters

parts – Components of the path, e.g. dir, subdir, filename.ext

Returns

complete file path as a single string

Example:

*** Tasks ***
Join path together
    Join path    output/nested    folder
list_directories_in_directory(path: Optional[Union[str, Path]] = None) list

Lists all the directories in the given directory, relative to it.

Parameters

path – base directory for search, defaults to current working dir

Returns

list of directories in selected directory

Example:

*** Tasks  ***
List directories
    ${directories}=    List directories in directory    devdata
    FOR    ${path}    IN    @{directories}
        Log    ${path}
    END
list_files_in_directory(path: Optional[Union[str, Path]] = None) list

Lists all the files in the given directory, relative to it.

Parameters

path – base directory for search, defaults to current working directory

Returns

list of files in directory

Example:

*** Tasks  ***
List directory file
    ${files}=    List files in directory    output
    FOR    ${file}    IN    @{files}
        Log    ${file}
    END
log_directory_tree(path: Optional[Union[str, Path]] = None) None

Logs all the files in the directory recursively.

Parameters

path – base directory to start from, defaults to current working dir

Example:

*** Tasks  ***
List directory tree
    Log directory tree
move_directory(source: Union[str, Path], destination: Union[str, Path], overwrite: bool = False) None

Move a directory from source path to destination path.

Parameters
  • source – source directory path for moving

  • destination – path to move to

  • overwrite – replace destination directory if it already exists (defaults to False)

Example:

*** Tasks ***
Move a directory
    Move directory    output    temp
move_file(source: Union[str, Path], destination: Union[str, Path], overwrite: bool = False) None

Move a file from source path to destination path, optionally overwriting the destination.

Parameters
  • source – source file path for moving

  • destination – path to move to

  • overwrite – replace destination file if it already exists (defaults to False)

Example:

*** Tasks ***
Move a file
    Create directory    temp
    Move file    output/log.html    temp/log.html
move_files(sources: List[Union[str, Path]], destination: Union[str, Path], overwrite: bool = False) None

Move multiple files to the destination folder.

Parameters
  • sources – list of files to move

  • destination – path to move destination

  • overwrite – replace destination files if they already exist

Example:

*** Tasks ***
Move some files
    Create directory    temp
    Move files    output/log.html    output/output.xml    temp
normalize_path(path: Union[str, Path]) str

Removes redundant separators or up-level references from path.

Parameters

path – path that will be normalized

Returns

path to file as a string

Example:

*** Tasks ***
Get normal path
    # Normalized path becomes ../inputs/input.xlsx
    ${normalized_path}=    Normalize path    ..//inputs/./new/../input.xlsx
    Create work items    ${normalized_path}
read_binary_file(path: Union[str, Path]) bytes

Reads a file in binary mode and returns the content. Does not attempt to decode the content in any way.

Parameters

path – path to file to read

Returns

the file content as bytes

Example:

*** Tasks ***
Read picture as binary
    ${pictures}=    Find files    **/*.png
    FOR    ${picture}    IN    @{pictures}
        Read binary file    ${picture}
    END
read_file(path: Union[str, Path], encoding: str = 'utf-8') str

Reads a file as text, with given encoding, and returns the content.”

See `Find Files` for usage example.

Parameters
  • path – path to file to read

  • encoding – character encoding of file (default utf-8)

Returns

file content as string

remove_directory(path: Union[str, Path], recursive: bool = False) None

Removes the given directory, and optionally everything it contains.

Parameters
  • path – path to directory

  • recursive – remove all subdirectories and files (default to False)

Example:

*** Tasks ***
Delete a directory
    Remove directory    output    recursive=${True}
remove_file(path: Union[str, Path], missing_ok: bool = True) None

Removes the given file.

Parameters
  • path – path to the file to remove

  • missing_ok – ignore non-existent file (defaults to True)

Example:

*** Tasks ***
Delete a file
    Remove file    output/log.html
remove_files(*paths: Union[str, Path], missing_ok: bool = True) None

Removes multiple files.

Parameters
  • paths – paths to files to be removed

  • missing_ok – ignore non-existent files (default to True)

Example:

*** Tasks ***
Delete some files
    Remove files    output/log.html    output/output.xml
run_keyword_if_file_exists(path: Union[str, Path], keyword: str, *args) None

If file exists at path, execute given keyword with arguments.

Parameters
  • path – path to file to inspect

  • keyword – Robot Framework keyword to execute

  • args – arguments to keyword

Example:

*** Tasks ***
Execute if orders exists
    Run keyword if file exists    orders.xlsx    Process orders
touch_file(path: Union[str, Path]) None

Creates a file with no content, or if file already exists, updates the modification and access times.

Parameters

path – path to file which is touched

wait_until_created(path: Union[str, Path], timeout: Union[int, float] = 5.0) str

Poll path until it exists, or raise exception if timeout is reached.

Parameters
  • path – path to poll

  • timeout – time in seconds until keyword fails

Returns

path to the created file as a string

Example:

*** Tasks ***
Wait for existence
    Wait until created    orders.xlsx    10
    Process orders    orders.xlsx
wait_until_modified(path: Union[str, Path], timeout: Union[int, float] = 5.0) str

Poll path until it has been modified after the keyword was called, or raise exception if timeout is reached.

Parameters
  • path – path to poll

  • timeout – time in seconds until keyword fails

Returns

path to the modified file as a string

Example:

*** Tasks ***
Wait for change
    Wait until modified    orders.xlsx    10
    Process orders    orders.xlsx
wait_until_removed(path: Union[str, Path], timeout: Union[int, float] = 5.0) None

Poll path until it doesn’t exist, or raise exception if timeout is reached.

Parameters
  • path – path to poll

  • timeout – time in seconds until keyword fails

exception RPA.FileSystem.TimeoutException

Bases: Exception

Exception raised from wait-prefixed keywords

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.