SPPAS 4.22

https://sppas.org/

Module sppas.src.utils

Class sppasDirUtils

Description

Utility directory manager for SPPAS.

Example
 >>> sd = sppasDirUtils("my-path")
 >>> print(sd.get_files())

Constructor

Create a sppasDirUtils instance.

Parameters
  • dirname: (str) Name of the current directory
View Source
def __init__(self, dirname):
    """Create a sppasDirUtils instance.

    :param dirname: (str) Name of the current directory

    """
    self._dirname = dirname

Public functions

get_files

Return the list of files of the directory.

Parameters
  • extension: (str) extension of files to filter the dir content
  • recurs: (bool) Find files recursively
Returns
  • a list of files
Raises

IOError

View Source
def get_files(self, extension, recurs=True):
    """Return the list of files of the directory.

        :param extension: (str) extension of files to filter the dir content
        :param recurs: (bool) Find files recursively
        :returns: a list of files
        :raises: IOError

        """
    if self._dirname is None:
        return []
    if os.path.exists(self._dirname) is False:
        raise NoDirectoryError(dirname=self._dirname)
    return sppasDirUtils.dir_entries(self._dirname, extension, recurs)

dir_entries

Return a list of file names found in directory 'dir_name'.

If 'subdir' is True, recursively access subdirectories under 'dir_name'. Additional argument, if any, is file extension to match filenames.

Parameters
  • dir_name
  • extension
  • subdir
View Source
@staticmethod
def dir_entries(dir_name, extension=None, subdir=True):
    """Return a list of file names found in directory 'dir_name'.

        If 'subdir' is True, recursively access subdirectories under
        'dir_name'. Additional argument, if any, is file extension to
        match filenames.

        """
    if extension is None:
        extension = '*'
    if extension.startswith('.') is False and extension != '*':
        extension = '.' + extension
    file_list = []
    for dfile in os.listdir(dir_name):
        dirfile = os.path.join(dir_name, dfile)
        if os.path.isfile(dirfile) is True:
            if extension == '*':
                file_list.append(dirfile)
            else:
                fname, fext = os.path.splitext(dirfile)
                if fext.lower() == extension.lower():
                    file_list.append(dirfile)
        elif os.path.isdir(dirfile) is True and subdir is True:
            file_list.extend(sppasDirUtils.dir_entries(dirfile, extension, subdir))
    return file_list