[18] | 1 | """Useful tools for manipulating files and directories |
---|
| 2 | """ |
---|
| 3 | |
---|
| 4 | def make_filename(s): |
---|
| 5 | """Transform argument string into a suitable filename |
---|
| 6 | """ |
---|
| 7 | |
---|
| 8 | s = s.strip() |
---|
| 9 | s = s.replace(' ', '_') |
---|
| 10 | #s = s.replace('(', '{') |
---|
| 11 | #s = s.replace(')', '}') |
---|
| 12 | s = s.replace('(', '') |
---|
| 13 | s = s.replace(')', '') |
---|
| 14 | s = s.replace('__', '_') |
---|
| 15 | |
---|
| 16 | return s |
---|
| 17 | |
---|
| 18 | |
---|
| 19 | def check_dir(path, verbose=None): |
---|
| 20 | """Check that specified path exists. |
---|
| 21 | If path does not exist it will be created if possible |
---|
| 22 | |
---|
| 23 | USAGE: |
---|
| 24 | checkdir(path, verbose): |
---|
| 25 | |
---|
| 26 | ARGUMENTS: |
---|
| 27 | path -- Directory |
---|
| 28 | verbose -- Flag verbose output (default: None) |
---|
| 29 | |
---|
| 30 | RETURN VALUE: |
---|
| 31 | Verified path including trailing separator |
---|
| 32 | |
---|
| 33 | """ |
---|
| 34 | |
---|
| 35 | import os, sys |
---|
| 36 | import os.path |
---|
| 37 | |
---|
| 38 | if sys.platform in ['nt', 'dos', 'win32', 'what else?']: |
---|
| 39 | unix = 0 |
---|
| 40 | else: |
---|
| 41 | unix = 1 |
---|
| 42 | |
---|
| 43 | |
---|
| 44 | if path[-1] != os.sep: |
---|
| 45 | path = path + os.sep # Add separator for directories |
---|
| 46 | |
---|
| 47 | path = os.path.expanduser(path) # Expand ~ or ~user in pathname |
---|
| 48 | if not (os.access(path,os.R_OK and os.W_OK) or path == ''): |
---|
| 49 | try: |
---|
| 50 | exitcode=os.mkdir(path) |
---|
| 51 | |
---|
| 52 | # Change access rights if possible |
---|
| 53 | # |
---|
| 54 | if unix: |
---|
| 55 | exitcode=os.system('chmod 775 '+path) |
---|
| 56 | else: |
---|
| 57 | pass # FIXME: What about acces rights under Windows? |
---|
| 58 | |
---|
| 59 | if verbose: print 'MESSAGE: Directory', path, 'created.' |
---|
| 60 | |
---|
| 61 | except: |
---|
| 62 | print 'WARNING: Directory', path, 'could not be created.' |
---|
| 63 | if unix: |
---|
| 64 | path = '/tmp/' |
---|
| 65 | else: |
---|
| 66 | path = 'C:' |
---|
| 67 | |
---|
| 68 | print 'Using directory %s instead' %path |
---|
| 69 | |
---|
| 70 | return(path) |
---|
| 71 | |
---|
| 72 | |
---|
| 73 | |
---|
| 74 | def del_dir(path): |
---|
| 75 | """Recursively delete directory path and all its contents |
---|
| 76 | """ |
---|
| 77 | |
---|
| 78 | import os |
---|
| 79 | |
---|
| 80 | if os.path.isdir(path): |
---|
| 81 | for file in os.listdir(path): |
---|
| 82 | X = os.path.join(path, file) |
---|
| 83 | |
---|
| 84 | |
---|
| 85 | if os.path.isdir(X) and not os.path.islink(X): |
---|
| 86 | del_dir(X) |
---|
| 87 | else: |
---|
| 88 | try: |
---|
| 89 | os.remove(X) |
---|
| 90 | except: |
---|
| 91 | print "Could not remove file %s" %X |
---|
| 92 | |
---|
| 93 | os.rmdir(path) |
---|
| 94 | |
---|
| 95 | |
---|
| 96 | |
---|
| 97 | |
---|