1 | n/a | from builtins import open as _orig_open |
---|
2 | n/a | |
---|
3 | n/a | def open(file, mode='r', bufsize=-1): |
---|
4 | n/a | if 'w' not in mode: |
---|
5 | n/a | return _orig_open(file, mode, bufsize) |
---|
6 | n/a | import os |
---|
7 | n/a | backup = file + '~' |
---|
8 | n/a | try: |
---|
9 | n/a | os.unlink(backup) |
---|
10 | n/a | except OSError: |
---|
11 | n/a | pass |
---|
12 | n/a | try: |
---|
13 | n/a | os.rename(file, backup) |
---|
14 | n/a | except OSError: |
---|
15 | n/a | return _orig_open(file, mode, bufsize) |
---|
16 | n/a | f = _orig_open(file, mode, bufsize) |
---|
17 | n/a | _orig_close = f.close |
---|
18 | n/a | def close(): |
---|
19 | n/a | _orig_close() |
---|
20 | n/a | import filecmp |
---|
21 | n/a | if filecmp.cmp(backup, file, shallow=False): |
---|
22 | n/a | import os |
---|
23 | n/a | os.unlink(file) |
---|
24 | n/a | os.rename(backup, file) |
---|
25 | n/a | f.close = close |
---|
26 | n/a | return f |
---|