diff python/utils.py @ 1021:16932cefabc1

work on paths in line with new configurations from tracker
author Nicolas Saunier <nicolas.saunier@polymtl.ca>
date Tue, 05 Jun 2018 17:02:28 -0400
parents 4f3387a242a1
children b7689372c0ec
line wrap: on
line diff
--- a/python/utils.py	Tue Jun 05 14:33:31 2018 -0400
+++ b/python/utils.py	Tue Jun 05 17:02:28 2018 -0400
@@ -5,6 +5,7 @@
 import matplotlib.pyplot as plt
 from datetime import time, datetime
 from argparse import ArgumentTypeError
+from pathlib import Path
 from math import sqrt, ceil, floor
 from scipy.stats import kruskal, shapiro, lognorm
 from scipy.spatial import distance
@@ -971,31 +972,42 @@
     'cleans filenames obtained when contatenating figure characteristics'
     return s.replace(' ','-').replace('.','').replace('/','-').replace(',','')
 
+def getRelativeFilename(parentPath, filename):
+    'Returns filename if absolute, otherwise parentPath/filename as string'
+    filePath = Path(filename)
+    if filePath.is_absolute():
+        return filename
+    else:
+        return str(parentPath/filePath)
+
 def listfiles(dirname, extension, remove = False):
     '''Returns the list of files with the extension in the directory dirname
     If remove is True, the filenames are stripped from the extension'''
-    from os import listdir
-    tmp = [f for f in listdir(dirname) if f.endswith(extension)]
-    tmp.sort()
-    if remove:
-        return [removeExtension(f, extension) for f in tmp]
+    d = Path(dirname)
+    if d.is_dir():
+        tmp = [str(f) for f in d.glob('*.extension')]
+        if remove:
+            return [removeExtension(f, extension) for f in tmp]
+        else:
+            return tmp
     else:
-        return tmp
+        print(dirname+' is not a directory')
+        return []
 
 def mkdir(dirname):
     'Creates a directory if it does not exist'
-    import os
-    if not os.path.exists(dirname):
-        os.mkdir(dirname)
+    p = Path(dirname)
+    if not p.exists():
+        p.mkdir()
     else:
         print(dirname+' already exists')
 
 def removeFile(filename):
     '''Deletes the file while avoiding raising an error 
     if the file does not exist'''
-    import os
-    if (os.path.exists(filename)):
-        os.remove(filename)
+    f = Path(filename)
+    if (f.exists()):
+        f.unlink()
     else:
         print(filename+' does not exist')