def atomic(dst, encoding='utf-8'):
"""Open a temporary file for writing using the given encoding.
The context manager returns an open file object, into which you can write
text or bytes depending on the encoding it was opened with. Upon exit,
the temporary file is moved atomically to the destination. If an
exception occurs, the temporary file is removed.
:param dst: The path name of the target file.
:param encoding: The encoding to use for the open file. If None, then
file is opened in binary mode.
"""
directory = os.path.dirname(dst)
mode = 'wb' if encoding is None else 'wt'
with ExitStack() as resources:
fp = resources.enter_context(NamedTemporaryFile(
mode=mode, encoding=encoding, dir=directory, delete=False))
yield fp
os.rename(fp.name, dst)
评论列表
文章目录