aiopathlib: Pathlib support for asyncio
If you are not using aiofiles,
anyio.Pathis another choice:
from datetime import datetime
from anyio import Path # pip install anyio
filepath = Path(__file__)
another = filepath.parent / 'sub_dirpath' / 'filename.ext'
if await another.exists():
content = await another.read_bytes()
elif not await another.parent.exists():
await another.parent.mkdir(parents=True)
else:
await another.write_bytes(b'1')
# glob/stat/remove
async for p in filepath.parent.glob('*'):
if await p.is_file():
stat = await p.stat()
create_time = datetime.fromtimestamp(stat.st_ctime)
update_time = datetime.fromtimestamp(stat.st_mtime)
await p.unlink() # remove file
print(f'{p} created at: {create_time}, modified at: {update_time}, removed at: {datetime.now()}')
See more at: https://github.com/agronholm/anyio
aiopathlib is written in Python, for handling local disk files in asyncio applications.
Base on aiofiles and just like pathlib, but use await.
with open('filename', 'w') as fp:
fp.write('{"msg":"My file contents"}')
apath = aiopathlib.AsyncPath('filename')
text = await apath.read_text()
print(repr(text))
# '{"msg":"My file contents"}'
content = await apath.read_bytes()
print(content)
# b'{"msg":"My file contents"}'
data = await apath.read_json()
print(data)
# {"msg": "My file contents"}
Asynchronous interface to create folder.
from aiopathlib import AsyncPath
apath = AsyncPath('dirname/subpath')
if not await apath.exists():
await apath.mkdir(parents=True)
Features
- a file API very similar to Python's standard package
pathlib, blocking API - support for buffered and unbuffered binary files, and buffered text files
- support for
async/await(:PEP:492) constructs
Installation
To install aiopathlib, simply:
$ pip install aiopathlib
Usage
These functions are awaitable
read_textread_bytesread_jsonwrite_textwrite_byteswrite_jsonmkdirtouchexistsrenameunlinkrmdirremovestatlstatis_fileis_diris_symlinkis_fifois_mountis_block_deviceis_char_deviceis_socket
Example
Some common using cases:
from pashlib import Path
from aiopathlib import AsyncPath
filename = 'test.json'
ap = AsyncPath(filename)
p = Path(filename)
assert (await ap.exists()) == p.exists() == False
await ap.touch() # Create a empty file
assert (await ap.is_file()) == p.is_file() == True
assert (await ap.is_dir()) == p.is_dir() == False
assert (await ap.is_symlink()) == p.is_symlink() == False
for func in ('is_fifo', 'is_mount', 'is_block_device', 'is_char_device', 'is_socket'):
assert (await getattr(ap, func)()) == getattr(p, func)()
d = {'key': 'value'}
await ap.write_json(d) # == p.write_text(json.dumps(d))
assert (await ap.read_json()) == d # == json.loads(p.read_text())
assert (await ap.read_bytes()) == p.read_bytes() # b'{"key": "value"}'
assert (await ap.stat()) == p.stat()
assert (await ap.lstat()) == p.lstat()
ap = await ap.rename('test_dir') # == AsyncPath(p.rename('test_dir'))
await ap.remove() # == await ap.unlink() == p.unlink()
await ap.mkdir() # == p.mkdir()
await ap.resolve() # == AsyncPath(p.resolve())
# Synchronization functions
[Path(i) for i in ap.glob('*')] == list(p.glob('*'))
[Path(i) for i in ap.rglob('*')] == list(p.rglob('*'))
ap / 'filename' == ap.joinpath('filename') == AsyncPath(f'{ap}/filename')
str(AsyncPath('string-or-Path-or-AsyncPath')) == str(Path('string-or-Path-or-AsyncPath'))
ap.stem == p.stem
ap.suffix == p.suffix
Path(ap.with_name('xxx')) == p.with_name('xxx')
Path(ap.parent) == p.parent
...
History
See the CHANGELOG.md file for details.
Contributing
Contributions are very welcome.
Metadata
Release files for aiopathlib 0.7.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | |
|---|---|---|---|---|
| aiopathlib-0.7.0.tar.gz | 9.8 kB | Without provenance | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| aiopathlib-0.7.0-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 16.3 kB
Release files / aiopathlib-0.7.0.tar.gz
| Download URL | aiopathlib-0.7.0.tar.gz |
|---|---|
| Size | 9.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
476e4720119a6b199b429cabe62fcdce0751e9063679ac8c6ff6cf09612ca32f
|
|
BLAKE2b-256 checksum How to use checksums |
3b84de5f14b670d6bd27827bf8fd09b09bda0799cbaf3fedc8f9b87be2e17561
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.10.9 {"installer":{"name":"uv","version":"0.10.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / aiopathlib-0.7.0-py3-none-any.whl
| Download URL | aiopathlib-0.7.0-py3-none-any.whl |
|---|---|
| Size | 6.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
18085fee4795e75fc4e68392b45c9efbec6d1da7c906fc414999542bd8a27884
|
|
BLAKE2b-256 checksum How to use checksums |
238bce47b0ffef954a457c46bff4c445f7e3bc47bcbfc52d6cb11abf7128641d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.10.9 {"installer":{"name":"uv","version":"0.10.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Security for aiopathlib 0.7.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.