Create Directory in Robot Framework

Introduction

In this article you can get acquainted with an adapted version Create Directory from the library OperatingSystem.py

Code

Here is how directory creation is implemented in the library OperatingSystem.py from Robot Framework

for simplicity self._link can be replaced with print

self._error with raise RuntimeError

import os def create_directory(self, path): """Creates the specified directory. Also possible intermediate directories are created. Passes if the directory already exists, but fails if the path exists and is not a directory. """ path = self._absnorm(path) if os.path.isdir(path): self._link("Directory '%s' already exists.", path) elif os.path.exists(path): self._error("Path '%s' is not a directory." % path) else: os.makedirs(path) self._link("Created directory '%s'.", path)

Under the hood

A walkthrough of how create_directory() works.

Everything about OOP has been dropped and the error handling part has been shortened.

# OOP is removed from these examples import os from pathlib import Path from unicodedata import normalize UNIXY = os.sep == '/' WINDOWS = not UNIXY if WINDOWS: CASE_INSENSITIVE_FILESYSTEM = True else: try: CASE_INSENSITIVE_FILESYSTEM = os.listdir('/tmp') == os.listdir('/TMP') except OSError: CASE_INSENSITIVE_FILESYSTEM = False def create_directory(path): """Creates the specified directory. Also possible intermediate directories are created. Passes if the directory already exists, but fails if the path exists and is not a directory. """ path = abspath(normalize_path(path)) if os.path.isdir(path): print("Directory '%s' already exists.", path) elif os.path.exists(path): raise RuntimeError("Path '%s' is not a directory." % path) else: os.makedirs(path) print("Created directory '%s'.", path) def normalize_path(path, case_normalize=False): # OperatingSystem.py """Normalizes the given path. - Collapses redundant separators and up-level references. - Converts ``/`` to ``\`` on Windows. - Replaces initial ``~`` or ``~user`` by that user's home directory. - If ``case_normalize`` is given a true value (see `Boolean arguments`) on Windows, converts the path to all lowercase. - Converts ``pathlib.Path`` instances to ``str``. Examples: | ${path1} = | Normalize Path | abc/ | | ${path2} = | Normalize Path | abc/../def | | ${path3} = | Normalize Path | abc/./def//ghi | | ${path4} = | Normalize Path | ~robot/stuff | => - ${path1} = 'abc' - ${path2} = 'def' - ${path3} = 'abc/def/ghi' - ${path4} = '/home/robot/stuff' On Windows result would use ``\`` instead of ``/`` and home directory would be different. """ if isinstance(path, Path): path = str(path) else: path = path.replace('/', os.sep) path = os.path.normpath(os.path.expanduser(path)) # os.path.normcase doesn't normalize on OSX which also, by default, # has case-insensitive file system. Our robot.utils.normpath would # do that, but it's not certain would that, or other things that the # utility do, desirable. if case_normalize: path = os.path.normcase(path) return path or '.' def abspath(path, case_normalize=False): # robotpath.py """Replacement for os.path.abspath with some enhancements and bug fixes. 1. Non-Unicode paths are converted to Unicode using file system encoding. 2. Optionally lower-case paths on case-insensitive file systems. That includes Windows and also OSX in default configuration. 3. Turn ``c:`` into ``c:\`` on Windows instead of ``c:\current\path``. """ path = normpath(path, case_normalize) return normpath(os.path.abspath(path), case_normalize) def normpath(path, case_normalize=False): # robotpath.py """Replacement for os.path.normpath with some enhancements. 1. Convert non-Unicode paths to Unicode using the file system encoding. 2. NFC normalize Unicode paths (affects mainly OSX). 3. Optionally lower-case paths on case-insensitive file systems. That includes Windows and also OSX in default configuration. 4. Turn ``c:`` into ``c:\`` on Windows instead of keeping it as ``c:``. """ if isinstance(path, Path): path = str(path) elif not isinstance(path, str): path = system_decode(path) path = safe_str(path) # Handles NFC normalization on OSX path = os.path.normpath(path) if case_normalize and CASE_INSENSITIVE_FILESYSTEM: path = path.lower() if WINDOWS and len(path) == 2 and path[1] == ':': return path + '\' return path def system_decode(string): # encoding.py return string if isinstance(string, str) else safe_str(string) def safe_str(item): # unic.py return normalize('NFC', _safe_str(item)) def _safe_str(item): # unic.py if isinstance(item, str): return item if isinstance(item, (bytes, bytearray)): # Map each byte to Unicode code point with same ordinal. return item.decode('latin-1') try: return str(item) # Will stop adding dependencies here because ErrorDetails class # is to big for this example. # except Exception: # return _unrepresentable_object(item) except Exception as e: return f'<Unrepresentable object {type(item).__name__}. Error: {e}>' if __name__ == '__main__': create_directory("backup")

Article author: Andrei Olegovich