pathlibutil
pathlibutil.Path inherits from pathlib.Path with some useful built-in python functions.
Path().hexdigest()to calculate andPath().verify()for verification of hexdigest from a filePath.default_hashto configurate default hash algorithm forPathclass (default: 'md5')Path().size()to get size in bytes of a file or directoryPath().read_lines()to yield over all lines from a file until EOFcontextmanagerto change current working directory withwithstatementPath().copy()copy a file or directory to a new path destinationPath().delete()delete a file or directory-treePath().move()move a file or directory to a new path destinationPath().make_archive()creates andPath().unpack_archive()uncompresses an archive from a file or directoryPath.archive_formatsto get all available archive formats
Installation
pip install pathlibutil
7zip support
to handle 7zip archives, an extra package py7zr>=0.20.2 is required!
# install as extra dependency
pip install pathlibutil[7z]
Usage
from pathlibutil import Path
readme = Path('README.md')
print(f'File size: {readme.size()} Bytes')
Example 1
Read a file and print its content and some file information to stdout.
Path().read_lines()
from pathlib import Path
readme = Path('README.md')
print('File content'.center(80, '='))
for line in readme.read_lines(encoding='utf-8'):
print(line, end='')
print('EOF'.center(80, '='))
Example 2
Write a file with md5 checksums of all python files in the pathlibutil-directory.
Path().hexdigest()
from pathlib import Path
file = Path('pathlibutil.md5')
algorithm = file.suffix[1:]
with file.open('w') as f:
f.write(
f'# {algorithm} checksums generated with pathlibutil (https://pypi.org/project/pathlibutil/)\n\n')
i = 0
for i, filename in enumerate(Path('./pathlibutil').glob('*.py'), start=1):
f.write(f'{filename.hexdigest(algorithm)} *{filename}\n')
print(f'\nwritten: {i:>5} {algorithm}-hashes to: {file}')
Example 3
Read a file with md5 checksums and verify them.
Path().verify(),Path.default_hashandcontextmanager
from pathlib import Path
file = Path('pathlibutil.md5')
Path.default_hash = file.suffix[1:]
def no_comment(line: str) -> bool:
return not line.startswith('#')
with file.parent as cwd:
for line in filter(no_comment, file.read_lines()):
try:
digest, filename = line.strip().split(' *')
verification = Path(filename).verify(digest)
except ValueError as split_failed:
continue
except FileNotFoundError as verify_failed:
tag = 'missing'
else:
tag = 'ok' if verification else 'fail
print(f'{tag.ljust(len(digest), ".")} *{filename}')
Example 4
Search all pycache directories and free the memory.
Path().delete()andPath().size()
from pathlib import Path
mem = 0
i = 0
for i, cache in enumerate(Path('.').rglob('*/__pycache__/'), start=1):
cache_size = cache.size()
try:
cache.delete(recursive=True)
except OSError:
print(f'Failed to delete {cache}')
else:
mem += cache_size
print(f'{i} cache directories deleted, {mem / 2**20:.2f} MB freed.')
Example 5
Inherit from pathlibutil.Path to register new a archive format.
Specify a archive as keyword argument in the new subclass, which has to be the suffix without . of the archives.
Implement a classmethod _register_archive_format() to register new archive formats.
Path().make_archive(),Path.archive_formatsandPath().move()
import shutil
import pathlibutil
class RegisterFooBarFormat(pathlibutil.Path, archive='foobar'):
@classmethod
def _register_archive_format(cls):
"""
implement new register functions for given `archive`
"""
try:
import <required_package_name>
except ModuleNotFoundError:
raise ModuleNotFoundError(
'pip install <required_package_name>'
)
def pack_foobar(base_name, base_dir, owner=None, group=None, dry_run=None, logger=None):
"""callable that will be used to unpack archives.
Args:
base_name (`str`): name of the file to create
base_dir (`str`): directory to start archiving from, defaults to `os.curdir`
owner (`Any`, optional): as passed in `make_archive(*args, owner=None, **kwargs)`. Defaults to None.
group (`Any`, optional): as passed in `make_archive(*args, group=None, **kwargs)`. Defaults to None.
dry_run (`Any`, optional): as passed in `make_archive(*args, dry_run=None, **kwargs)`.
Defaults to None.
logger (`logging.Logger`, optional): as passed in `make_archive(*args, logger=None, **kwargs)`.
Defaults to None.
"""
raise NotImplementedError('implement your own pack function')
def unpack_foobar(archive, path, filter=None, extra_args=None):
"""callable that will be used to unpack archives.
Args:
archive (`str`): path of the archive
path (`str`): directory the archive must be extracted to
filter (`Any`, optional): as passed in `unpack_archive(*args, filter=None, **kwargs)`.
Defaults to None.
extra_args (`Sequence[Tuple[name, value]]`, optional): additional keyword arguments.
as passd in `register_unpack_format(*args, extra_args=None, **kwargs)`. Defaults to None.
"""
raise NotImplementedError('implement your own unpack function')
shutil.register_archive_format(
'foobar', pack_foobar, description='foobar archives'
)
shutil.register_unpack_format(
'foobar', ['.foo.bar'], unpack_foobar
)
file = pathlibutil.Path('README.md')
print(f"available archive formats: {file.archive_formats}")
archive = file.make_archive('README.foo.bar')
backup = archive.move('./backup/')
print(f'archive created: {archive.name} and moved to: {backup.parent}')
Metadata
Release files for pathlibutil 0.1.3
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 | Actions |
|---|---|---|---|---|
| pathlibutil-0.1.3.tar.gz | 6.6 kB | Without provenance | Details for pathlibutil-0.1.3.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| pathlibutil-0.1.3-py3-none-any.whl | Python 3 | none | any | Details for pathlibutil-0.1.3-py3-none-any.whl |
Total release size: 14.5 kB
Release files / pathlibutil-0.1.3.tar.gz
| Download URL | pathlibutil-0.1.3.tar.gz |
|---|---|
| Size | 6.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
7beab6dd89d05d8ae99d929fffa164b010a27f878d91e0b3632c866baa828717
|
|
BLAKE2b-256 checksum How to use checksums |
2ca09afcff33143315edfdf23ca7a2bb54fcc2cd9ff41373fe45ff8f76e66645
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
poetry/1.7.1 CPython/3.11.7 Linux/6.2.0-1018-azure
|
Release files / pathlibutil-0.1.3-py3-none-any.whl
| Download URL | pathlibutil-0.1.3-py3-none-any.whl |
|---|---|
| Size | 7.9 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
808f44c296380e9d3e892e7d68fdea9ea5d7aa8eba30cc0b55f10a54d38430bb
|
|
BLAKE2b-256 checksum How to use checksums |
eab886aaf03bf318dcf652dce25a0fbb2867092219a2faa03b2f470a7a368ba1
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
poetry/1.7.1 CPython/3.11.7 Linux/6.2.0-1018-azure
|
Security for pathlibutil 0.1.3
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.