Prevent fd leak if copystat fails

This commit is contained in:
Kovid Goyal
2021-07-16 08:46:04 +05:30
parent 040a152f1f
commit 01ce0e1d1a

View File

@@ -24,8 +24,8 @@ posix_template = '''
def atomic_write(path: str, data: Union[str, bytes]) -> None:
mode = 'w' + ('b' if isinstance(data, bytes) else '')
fd, tpath = mkstemp(dir=os.path.dirname(path), text=isinstance(data, str))
shutil.copystat(path, tpath)
with open(fd, mode) as f:
shutil.copystat(path, tpath)
f.write(data)
os.rename(tpath, path)