24 Utilities for safe file IO
26 from contextlib
import contextmanager
34 """Make a directory in a manner avoiding race conditions"""
35 if directory !=
"" and not os.path.exists(directory):
37 os.makedirs(directory)
40 if e.errno != errno.EEXIST:
45 """Set a file mode according to the user's umask"""
47 umask = os.umask(0o077)
51 os.chmod(filename, (~umask & 0o666))
56 """Context manager to get a file that can be written only once and all other writes will succeed only if
57 they match the inital write.
59 The context manager provides a temporary file object. After the user is done, the temporary file becomes
60 the permanent file if the file at name does not already exist. If the file at name does exist the
61 temporary file is compared to the file at name. If they are the same then this is good and the temp file
62 is silently thrown away. If they are not the same then a runtime error is raised.
64 outDir, outName = os.path.split(name)
66 temp = tempfile.NamedTemporaryFile(mode=
"w", dir=outDir, prefix=outName, delete=
False)
74 os.symlink(temp.name, name)
77 os.rename(temp.name, name)
82 if e.errno != errno.EEXIST:
84 filesMatch = filecmp.cmp(temp.name, name, shallow=
False)
92 raise RuntimeError(
"Written file does not match existing file.")
97 """Context manager to create a file in a manner avoiding race conditions
99 The context manager provides a temporary file object. After the user is done,
100 we move that file into the desired place and close the fd to avoid resource
103 outDir, outName = os.path.split(name)
105 with tempfile.NamedTemporaryFile(mode=
"w", dir=outDir, prefix=outName, delete=
False)
as temp:
109 os.rename(temp.name, name)
115 """Context manager for creating a file in a manner avoiding race conditions
117 The context manager provides a temporary filename with no open file descriptors
118 (as this can cause trouble on some systems). After the user is done, we move the
119 file into the desired place.
121 outDir, outName = os.path.split(name)
123 temp = tempfile.NamedTemporaryFile(mode=
"w", dir=outDir, prefix=outName, delete=
False)
129 os.rename(tempName, name)
def FileForWriteOnceCompareSame