| 1 |
|
| 2 |
|
| 3 |
from os import makedirs |
| 4 |
from os.path import dirname, isdir, isfile |
| 5 |
|
| 6 |
def createDirFor(filePath): |
| 7 |
'''Creates an output directory for containing the given file path. |
| 8 |
Nothing happens if the directory already exsits. |
| 9 |
''' |
| 10 |
dirPath = dirname(filePath) |
| 11 |
if dirPath and not isdir(dirPath): |
| 12 |
makedirs(dirPath) |
| 13 |
|
| 14 |
def rewriteIfChanged(path, lines): |
| 15 |
'''Writes the file with the given path if it does not exist yet or if its |
| 16 |
contents should change. The contents are given by the "lines" sequence. |
| 17 |
Returns True if the file was (re)written, False otherwise. |
| 18 |
''' |
| 19 |
newLines = [ line + '\n' for line in lines ] |
| 20 |
|
| 21 |
if isfile(path): |
| 22 |
inp = open(path, 'r') |
| 23 |
try: |
| 24 |
oldLines = inp.readlines() |
| 25 |
finally: |
| 26 |
inp.close() |
| 27 |
|
| 28 |
if newLines == oldLines: |
| 29 |
print('Up to date: %s' % path) |
| 30 |
return False |
| 31 |
else: |
| 32 |
print('Updating %s...' % path) |
| 33 |
else: |
| 34 |
print('Creating %s...' % path) |
| 35 |
createDirFor(path) |
| 36 |
|
| 37 |
out = open(path, 'w') |
| 38 |
try: |
| 39 |
out.writelines(newLines) |
| 40 |
finally: |
| 41 |
out.close() |
| 42 |
return True |