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