diff python/utils.py @ 0:aed8eb63cdde

initial commit with non-functional python code for NGSIM
author Nicolas Saunier <nico@confins.net>
date Sun, 18 Oct 2009 22:29:24 -0400
parents
children de5642925615
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/python/utils.py	Sun Oct 18 22:29:24 2009 -0400
@@ -0,0 +1,63 @@
+#! /usr/bin/env python
+''' Generic utilities.'''
+
+#from numpy import *
+#from pylab import *
+
+__metaclass__ = type
+
+commentChar = '#';
+
+def openCheck(filename, option = 'r', quit = False):
+    '''Open file filename in read mode by default
+    and checks it is open
+
+    >>> f = openCheck('non_existant_file.txt')
+    File non_existant_file.txt could not be opened.
+    '''
+    try:
+        return open(filename, option)
+    except IOError:
+        print 'File %s could not be opened.' % filename
+        if quit:
+            from sys import exit
+            exit()
+        return None
+
+def readline(f):
+    '''Modified readline function to skip comments.'''
+    s = f.readline()
+    while (len(s) > 0) and s.startswith(commentChar):
+        s = f.readline()
+    return s.strip()
+
+def removeExtension(filename, delimiter = '.'):
+    '''Returns the filename minus the extension (all characters after last .)
+    >>> removeExtension('test-adfasdf.asdfa.txt')
+    'test-adfasdf.asdfa'
+    >>> removeExtension('test-adfasdf')
+    'test-adfasdf'
+    '''
+    i = filename.rfind(delimiter)
+    if i>0:
+        return filename[:i]
+    else:
+        return filename
+
+def listfiles(dirname, extension, remove = False):
+    '''Returns the list of files with the extension in the directory dirname'''
+    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]
+    else:
+        return tmp
+
+
+
+
+if __name__ == "__main__":
+    import doctest
+    doctest.testmod()
+    #doctest.testfile("example.txt")