Utility file manager for SPPAS.
Example
>>> sf = sppasFileUtils("path/myfile.txt")
>>> print(sf.exists())
Example
>>> sf = sppasFileUtils()
>>> sf.set_random()
>>> fn = sf.get_filename() + ".txt"
Utility file manager for SPPAS.
>>> sf = sppasFileUtils("path/myfile.txt")
>>> print(sf.exists())
>>> sf = sppasFileUtils()
>>> sf.set_random()
>>> fn = sf.get_filename() + ".txt"
Create a sppasFileUtils instance.
def __init__(self, filename=None):
"""Create a sppasFileUtils instance.
:param filename: (str) Name of the current file
"""
self._filename = filename
Return the current filename.
def get_filename(self):
"""Return the current filename."""
return self._filename
Set randomly a basename, i.e. a filename without extension.
def set_random(self, root='sppas_tmp', add_today=True, add_pid=True):
"""Set randomly a basename, i.e. a filename without extension.
:param root: (str) String to start the filename
:param add_today: (bool) Add today's information to the filename
:param add_pid: (bool) Add the process PID to the filename
:returns: a random name of a non-existing file or directory
"""
tempdir = tempfile.gettempdir()
name = '/'
while os.path.exists(name) is True:
filename = root + '_'
if add_today:
today = str(date.today())
filename = filename + today + '_'
if add_pid:
pid = str(os.getpid())
filename = filename + pid + '_'
filename = filename + '{:06d}'.format(int(random.random() * 999999))
name = os.path.join(tempdir, filename)
self._filename = name
return name
Check if the file exists, or exists in a given directory.
Case-insensitive test on all platforms.
def exists(self, directory=None):
"""Check if the file exists, or exists in a given directory.
Case-insensitive test on all platforms.
:param directory: (str) Optional directory to test if a file exists.
:returns: the filename (including directory) or None
"""
if directory is None:
directory = os.path.dirname(self._filename)
for x in os.listdir(directory):
if os.path.basename(self._filename.lower()) == x.lower():
return os.path.join(directory, x)
return None
Set filename without whitespace.
def clear_whitespace(self):
"""Set filename without whitespace.
:returns: new filename with spaces replaced by underscores.
"""
sp = sppasUnicode(self._filename)
self._filename = sp.clear_whitespace()
return self._filename
Set filename with only US-ASCII characters.
def to_ascii(self):
"""Set filename with only US-ASCII characters.
:returns: new filename with non-ASCII chars replaced by underscores.
"""
sp = sppasUnicode(self._filename)
self._filename = sp.to_ascii()
return self._filename
Set filename without whitespace and with only US-ASCII characters.
def format(self):
"""Set filename without whitespace and with only US-ASCII characters.
:returns: new filename with non-ASCII characters and spaces replaced by underscores.
"""
self.clear_whitespace()
self.to_ascii()
return self._filename