mt.path

Additional functions dealing with paths.

Instead of:

from os import path

You do:

from mt import path

It will import the path package plus the additional stuff implemented here.

Please see Python package os.path for more details.

Functions

  • exists_asyn(): An asyn function that checks if a path exists, regardless of it being a file or a folder.

  • exists_timeout(): Checks if a path exists for a number of seconds.

  • remove_asyn(): An asyn function that removes a path completely, regardless of it being a file or a folder.

  • remove(): Removes a path completely, regardless of it being a file or a folder.

  • make_dirs(): Convenient invocation of os.makedirs(path, exist_ok=True). If shared is True, every newly created folder will have permission 0o775.

  • lock(): Returns the current MROW lock for a given path.

  • rename_asyn(): An asyn function that renames a file or a directory.

  • rename(): Renames a file or a directory.

  • walk(): Directory tree generator.

  • stat_asyn(): An asyn function that performs a stat system call on the given path.

  • stat(): Performs a stat system call on the given path.

  • glob(): Return a list of paths matching a pathname pattern.

async mt.path.exists_asyn(path: Path | str, context_vars: dict = {})

An asyn function that checks if a path exists, regardless of it being a file or a folder.

Parameters:
  • path (str) – a path to a link, a file or a directory

  • context_vars (dict) – a dictionary of context variables within which the function runs. It must include context_vars[‘async’] to tell whether to invoke the function asynchronously or not.

Returns:

whether or not the path exists

Return type:

bool

Notes

Just like os.path.exists(). The function returns False for broken symbolic links.

mt.path.exists_timeout(path: str, timeout: float = 1.0) bool

Checks if a path exists for a number of seconds.

Call this function rarely as the wrapping for the function to be run in a background thread is expensive.

Parameters:
  • path (str) – a path to a link, a file or a directory

  • timeout (float) – number of seconds to wait before timeout.

Returns:

whether or not the path exists

Return type:

bool

Raises:

func_timeout.FunctionTimeout – if the function times out

async mt.path.remove_asyn(path: Path | str, context_vars: dict = {})

An asyn function that removes a path completely, regardless of it being a file or a folder.

If the path does not exist, do nothing.

Parameters:
  • path (str) – a path to a link, a file or a directory

  • context_vars (dict) – a dictionary of context variables within which the function runs. It must include context_vars[‘async’] to tell whether to invoke the function asynchronously or not.

mt.path.remove(path: Path | str)

Removes a path completely, regardless of it being a file or a folder.

If the path does not exist, do nothing.

Parameters:

path (str) – a path to a link, a file or a directory

mt.path.make_dirs(path: Path | str, shared: bool = True)

Convenient invocation of os.makedirs(path, exist_ok=True). If shared is True, every newly created folder will have permission 0o775.

mt.path.lock(path: Path | str, to_write: bool = False)

Returns the current MROW lock for a given path.

Parameters:
  • path (str) – local path

  • to_write (bool) – whether lock to write or to read

Returns:

lock – an instance of WriteRWLock if to_write is True, otherwise an instance of ReadRWLock

Return type:

ReadRWLock or WriteRWLock

async mt.path.rename_asyn(src: Path | str, dst: Path | str, context_vars: dict = {}, overwrite: bool = False)

An asyn function that renames a file or a directory.

Parameters:
  • src (str) – path to the source file or directory

  • dst (path) – new name also as a path

  • overwrite (bool) – whether or not (default) to overwrite the destination file if it exists

  • context_vars (dict) – a dictionary of context variables within which the function runs. It must include context_vars[‘async’] to tell whether to invoke the function asynchronously or not.

Raises:

FileExistsError – if the target file exists

mt.path.rename(src: Path | str, dst: Path | str, overwrite: bool = False)

Renames a file or a directory.

Parameters:
  • src (str) – path to the source file or directory

  • dst (path) – new name also as a path

  • overwrite (bool) – whether or not (default) to overwrite the destination file if it exists

mt.path.walk(top, topdown=True, onerror=None, followlinks=False)

Directory tree generator.

For each directory in the directory tree rooted at top (including top itself, but excluding ‘.’ and ‘..’), yields a 3-tuple

dirpath, dirnames, filenames

dirpath is a string, the path to the directory. dirnames is a list of the names of the subdirectories in dirpath (excluding ‘.’ and ‘..’). filenames is a list of the names of the non-directory files in dirpath. Note that the names in the lists are just names, with no path components. To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name).

If optional arg ‘topdown’ is true or not specified, the triple for a directory is generated before the triples for any of its subdirectories (directories are generated top down). If topdown is false, the triple for a directory is generated after the triples for all of its subdirectories (directories are generated bottom up).

When topdown is true, the caller can modify the dirnames list in-place (e.g., via del or slice assignment), and walk will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search, or to impose a specific order of visiting. Modifying dirnames when topdown is false has no effect on the behavior of os.walk(), since the directories in dirnames have already been generated by the time dirnames itself is generated. No matter the value of topdown, the list of subdirectories is retrieved before the tuples for the directory and its subdirectories are generated.

By default errors from the os.scandir() call are ignored. If optional arg ‘onerror’ is specified, it should be a function; it will be called with one argument, an OSError instance. It can report the error to continue with the walk, or raise the exception to abort the walk. Note that the filename is available as the filename attribute of the exception object.

By default, os.walk does not follow symbolic links to subdirectories on systems that support them. In order to get this functionality, set the optional argument ‘followlinks’ to true.

Caution: if you pass a relative pathname for top, don’t change the current working directory between resumptions of walk. walk never changes the current directory, and assumes that the client doesn’t either.

Example:

import os from os.path import join, getsize for root, dirs, files in os.walk(‘python/Lib/email’):

print(root, “consumes”, end=””) print(sum(getsize(join(root, name)) for name in files), end=””) print(“bytes in”, len(files), “non-directory files”) if ‘CVS’ in dirs:

dirs.remove(‘CVS’) # don’t visit CVS directories

async mt.path.stat_asyn(path: Path | str, dir_fd=None, follow_symlinks=True, context_vars: dict = {})

An asyn function that performs a stat system call on the given path.

Parameters:
  • path (str) – Path to be examined; can be string, bytes, a path-like object or open-file-descriptor int.

  • dir_fd (object, optional) – If not None, it should be a file descriptor open to a directory, and path should be a relative string; path will then be relative to that directory.

  • follow_symlinks (bool) – If False, and the last element of the path is a symbolic link, stat will examine the symbolic link itself instead of the file the link points to.

  • context_vars (dict) – a dictionary of context variables within which the function runs. It must include context_vars[‘async’] to tell whether to invoke the function asynchronously or not.

Returns:

the resulting instance

Return type:

os.stat_result

Notes

dir_fd and follow_symlinks may not be implemented on your platform. If they are unavailable, using them will raise a NotImplementedError.

It’s an error to use dir_fd or follow_symlinks when specifying path as an open file descriptor.

mt.path.stat(path: Path | str, dir_fd=None, follow_symlinks=True)

Performs a stat system call on the given path.

Parameters:
  • path (str) – Path to be examined; can be string, bytes, a path-like object or open-file-descriptor int.

  • dir_fd (object, optional) – If not None, it should be a file descriptor open to a directory, and path should be a relative string; path will then be relative to that directory.

  • follow_symlinks (bool) – If False, and the last element of the path is a symbolic link, stat will examine the symbolic link itself instead of the file the link points to.

Returns:

the resulting instance

Return type:

os.stat_result

Notes

dir_fd and follow_symlinks may not be implemented on your platform. If they are unavailable, using them will raise a NotImplementedError.

It’s an error to use dir_fd or follow_symlinks when specifying path as an open file descriptor.

mt.path.glob(pathname, *, recursive=False)

Return a list of paths matching a pathname pattern.

The pattern may contain simple shell-style wildcards a la fnmatch. However, unlike fnmatch, filenames starting with a dot are special cases that are not matched by ‘*’ and ‘?’ patterns.

If recursive is true, the pattern ‘**’ will match any files and zero or more directories and subdirectories.

Variables

mt.path.utime

Set the access and modified time of path.

path may always be specified as a string. On some platforms, path may also be specified as an open file descriptor.

If this functionality is unavailable, using it raises an exception.

If times is not None, it must be a tuple (atime, mtime);

atime and mtime should be expressed as float seconds since the epoch.

If ns is specified, it must be a tuple (atime_ns, mtime_ns);

atime_ns and mtime_ns should be expressed as integer nanoseconds since the epoch.

If times is None and ns is unspecified, utime uses the current time. Specifying tuples for both times and ns is an error.

If dir_fd is not None, it should be a file descriptor open to a directory,

and path should be relative; path will then be relative to that directory.

If follow_symlinks is False, and the last element of the path is a symbolic

link, utime will modify the symbolic link itself instead of the file the link points to.

It is an error to use dir_fd or follow_symlinks when specifying path

as an open file descriptor.

dir_fd and follow_symlinks may not be available on your platform.

If they are unavailable, using them will raise a NotImplementedError.

<built-in function utime>
mt.path.chmod

Change the access permissions of a file.

path

Path to be modified. May always be specified as a str, bytes, or a path-like object. On some platforms, path may also be specified as an open file descriptor. If this functionality is unavailable, using it raises an exception.

mode

Operating-system mode bitfield.

dir_fd

If not None, it should be a file descriptor open to a directory, and path should be relative; path will then be relative to that directory.

follow_symlinks

If False, and the last element of the path is a symbolic link, chmod will modify the symbolic link itself instead of the file the link points to.

It is an error to use dir_fd or follow_symlinks when specifying path as

an open file descriptor.

dir_fd and follow_symlinks may not be implemented on your platform.

If they are unavailable, using them will raise a NotImplementedError.

<built-in function chmod>
mt.path.listdir

Return a list containing the names of the files in the directory.

path can be specified as either str, bytes, or a path-like object. If path is bytes,

the filenames returned will also be bytes; in all other circumstances the filenames returned will be str.

If path is None, uses the path=’.’. On some platforms, path may also be specified as an open file descriptor;

the file descriptor must refer to a directory. If this functionality is unavailable, using it raises NotImplementedError.

The list is in arbitrary order. It does not include the special entries ‘.’ and ‘..’ even if they are present in the directory.

<built-in function listdir>