Utility directory manager for SPPAS.
Example
>>> sd = sppasDirUtils("my-path")
>>> print(sd.get_files())
Utility directory manager for SPPAS.
>>> sd = sppasDirUtils("my-path")
>>> print(sd.get_files())
Create a sppasDirUtils instance.
def __init__(self, dirname):
"""Create a sppasDirUtils instance.
:param dirname: (str) Name of the current directory
"""
self._dirname = dirname
Return the list of files of the directory.
IOError
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)
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.
@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