inherits from pathlib.Path with methods for hashing, copying, deleting and more
Project description
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_hash
to configurate default hash algorithm forPath
class (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 EOFcontextmanager
to change current working directory withwith
statementPath().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()
create andPath().unpack_archive()
an archive from a file or directory
Installation
pip install pathlibutil
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_hash
andcontextmanager
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 name
as keyword argument in the new subclass, which has to be the suffix of the archives.
Implement a classmethod _register_archive_format()
to register new archive formats.
Path().make_archive()
andPath().move()
import shutil
import pathlibutil
class RegisterRarFormat(pathlibutil.Path, name='rar'):
@classmethod
def _register_archive_format(cls):
"""
implement new register functions for given `name`
"""
try:
from pyunpack import Archive
except ModuleNotFoundError:
raise ModuleNotFoundError('pip install pyunpack')
else:
shutil.register_archive_format(
'rar', Archive, description='rar archive'
)
shutil.register_unpack_format(
'rar', ['.rar'], Archive
)
file = pathlibutil.Path('README.md')
print(f"available archive formats: {file.archive_formats}")
archive = file.make_archive('README.rar')
backup = archive.move('./backup/')
print(f'rar archive created: {archive.name} and moved to: {backup.parent}')
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
File details
Details for the file pathlibutil-0.1.2.tar.gz
.
File metadata
- Download URL: pathlibutil-0.1.2.tar.gz
- Upload date:
- Size: 6.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.7.1 CPython/3.11.7 Linux/6.2.0-1018-azure
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | d63c6bd37dab80dea716da7f7cdc662a61182627739c10e4487e3deb438f9c9b |
|
MD5 | 451e08e8a593327b1c2e0b60e689e93c |
|
BLAKE2b-256 | bfebd4f3d1ec973511f68049a549595da3122b1c17e91dd74c9145f6420ba70c |
File details
Details for the file pathlibutil-0.1.2-py3-none-any.whl
.
File metadata
- Download URL: pathlibutil-0.1.2-py3-none-any.whl
- Upload date:
- Size: 7.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.7.1 CPython/3.11.7 Linux/6.2.0-1018-azure
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 8a12e0edd7c120662ef7a292b8fe59636c9fb2c1434f81bda9e96dbe9e09dc83 |
|
MD5 | 15e6e9863ee0aa344fc7dafa333121ac |
|
BLAKE2b-256 | b83ba6e950802796903565cb3a85da2d1516b08cb6c51e43a52f03cfde320971 |