blob: d29716a93c98b3db6eef4c3720ff59738621eb34 [file] [log] [blame]
Guido van Rossumbaf06031998-08-25 14:06:55 +00001_orig_open = open
2
3class _BkFile:
4 def __init__(self, file, mode, bufsize):
5 import os
6 self.__filename = file
7 self.__backup = file + '~'
8 try:
9 os.unlink(self.__backup)
10 except os.error:
11 pass
12 try:
13 os.rename(file, self.__backup)
14 except os.error:
15 self.__backup = None
16 self.__file = _orig_open(file, mode, bufsize)
17 self.closed = self.__file.closed
18 self.fileno = self.__file.fileno
19 self.flush = self.__file.flush
20 self.isatty = self.__file.isatty
21 self.mode = self.__file.mode
22 self.name = self.__file.name
23 self.read = self.__file.read
24 self.readinto = self.__file.readinto
25 self.readline = self.__file.readline
26 self.readlines = self.__file.readlines
27 self.seek = self.__file.seek
28 self.softspace = self.__file.softspace
29 self.tell = self.__file.tell
30 self.truncate = self.__file.truncate
31 self.write = self.__file.write
32 self.writelines = self.__file.writelines
33
34 def close(self):
35 self.__file.close()
36 if self.__backup is None:
37 return
Guido van Rossum6664bb82000-04-28 13:31:52 +000038 import filecmp
39 if filecmp.cmp(self.__backup, self.__filename, shallow = 0):
Guido van Rossumbaf06031998-08-25 14:06:55 +000040 import os
41 os.unlink(self.__filename)
42 os.rename(self.__backup, self.__filename)
43
44def open(file, mode = 'r', bufsize = -1):
45 if 'w' not in mode:
46 return _orig_open(file, mode, bufsize)
47 return _BkFile(file, mode, bufsize)