`writer-cm` is a context manager allowing you to atomically write files given a file path.
Project description
writer-cm
is a context manager allowing you to atomically write files given a
file path.
Features
- Cross-platform atomic file writes powered by python-atomicwrites.
- Interface using a file path instead of a file handle, for more compatibility
with external libraries (e.g.
pandas.to_pickle
). - Automatically create missing directories and set their permissions.
- Automatically set the file permissions.
Installation
pip install writer-cm
Usage
Import and invoke writer_cm
as a context manager to obtain a pathlib.Path
object to which you can atomically write to:
from writer_cm import writer_cm
with writer_cm("file.txt") as temp:
# `temp` is a `pathlib.Path` object
with open(temp, mode="w") as fh:
fh.write("foo")
# file.txt is atomically written to upon leaving the context manager
with open("file.txt") as fh:
assert fh.read() == "foo"
writer_cm
can also automatically create missing directories and set their
permissions (which is done carefully as opposed to relying on
Path.mkdir
,
which itself notes that "[parents] are created with the default permissions
without taking mode into account"). Analogously, writer_cm
can also set the
file permissions too.
from stat import S_IRWXU, S_IRWXG, S_IRUSR, S_IWUSR
with writer_cm("dir1/dir2/dir3/file.txt",
dir_perms=S_IRWXU | S_IRWXG, # the default
file_perms=S_IRUSR, S_IWUSR, # the default
) as temp:
with open(temp, mode="w") as fh:
fh.write("foo")
# now `dir1/dir2/dir3` has been created with u=rwx,g=rwx permissions
# `dir1/dir2/dir3.file.txt` has been created with u=rw permissions
For more info on stat
, see the
official docs.
Finally, pass overwrite=True
to overwrite an already existing file; an error
is thrown otherwise:
with writer_cm("file.txt", overwrite=True) as temp:
with open(temp, mode="w") as fh:
fh.write("bar")
with open("file.txt") as fh:
assert fh.read() == "bar"
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for writer_cm-1.0.8-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | d2a9f545d7c5ba764ec5271588523cdd8f3a3234d5066b38184fa3d4410ac8c4 |
|
MD5 | efb43be717f7608a5b131af9efcfd198 |
|
BLAKE2b-256 | 795a4079cf7387c444290b34940ca79d451aa0744230471bf21be6363318e7f3 |