Mercurial Hosting > traffic-intelligence
comparison 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 |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:aed8eb63cdde |
---|---|
1 #! /usr/bin/env python | |
2 ''' Generic utilities.''' | |
3 | |
4 #from numpy import * | |
5 #from pylab import * | |
6 | |
7 __metaclass__ = type | |
8 | |
9 commentChar = '#'; | |
10 | |
11 def openCheck(filename, option = 'r', quit = False): | |
12 '''Open file filename in read mode by default | |
13 and checks it is open | |
14 | |
15 >>> f = openCheck('non_existant_file.txt') | |
16 File non_existant_file.txt could not be opened. | |
17 ''' | |
18 try: | |
19 return open(filename, option) | |
20 except IOError: | |
21 print 'File %s could not be opened.' % filename | |
22 if quit: | |
23 from sys import exit | |
24 exit() | |
25 return None | |
26 | |
27 def readline(f): | |
28 '''Modified readline function to skip comments.''' | |
29 s = f.readline() | |
30 while (len(s) > 0) and s.startswith(commentChar): | |
31 s = f.readline() | |
32 return s.strip() | |
33 | |
34 def removeExtension(filename, delimiter = '.'): | |
35 '''Returns the filename minus the extension (all characters after last .) | |
36 >>> removeExtension('test-adfasdf.asdfa.txt') | |
37 'test-adfasdf.asdfa' | |
38 >>> removeExtension('test-adfasdf') | |
39 'test-adfasdf' | |
40 ''' | |
41 i = filename.rfind(delimiter) | |
42 if i>0: | |
43 return filename[:i] | |
44 else: | |
45 return filename | |
46 | |
47 def listfiles(dirname, extension, remove = False): | |
48 '''Returns the list of files with the extension in the directory dirname''' | |
49 from os import listdir | |
50 tmp = [f for f in listdir(dirname) if f.endswith(extension)] | |
51 tmp.sort() | |
52 if remove: | |
53 return [removeExtension(f, extension) for f in tmp] | |
54 else: | |
55 return tmp | |
56 | |
57 | |
58 | |
59 | |
60 if __name__ == "__main__": | |
61 import doctest | |
62 doctest.testmod() | |
63 #doctest.testfile("example.txt") |