Atomicwrites¶
Description:
- Race-free assertion that the target file doesn’t yet exist.
Resources:
- [GitHub] https://github.com/untitaker/python-atomicwrites
- [Docs] https://python-atomicwrites.readthedocs.io/en/latest/#
Note:
- Whenever you are writing files to local filesystem, you cannot write to the '/' directory or you will get a permission denied error. Make a temporary directory first.
Example 1¶
Write a file to the local filesystem
In [ ]:
Copied!
from atomicwrites import atomic_write
from pathlib import Path
# Create the dir
tmp_path = "/tmp/ganymede_demo"
path = Path(tmp_path)
path.mkdir(parents=True, exist_ok=True)
# Define file path
file_ = "foo.txt"
fp = f"{tmp_path}/{file_}"
# Write the file to local
with atomic_write(fp, overwrite=True) as f:
f.write('Hello world.')
# "foo.txt" doesn't exist yet
# Now it does. Check it's contents
with open(fp, "r") as f:
print(f.read())
from atomicwrites import atomic_write
from pathlib import Path
# Create the dir
tmp_path = "/tmp/ganymede_demo"
path = Path(tmp_path)
path.mkdir(parents=True, exist_ok=True)
# Define file path
file_ = "foo.txt"
fp = f"{tmp_path}/{file_}"
# Write the file to local
with atomic_write(fp, overwrite=True) as f:
f.write('Hello world.')
# "foo.txt" doesn't exist yet
# Now it does. Check it's contents
with open(fp, "r") as f:
print(f.read())