herolib_python/lib/core/pathlib/pathlib.py
2025-08-05 15:48:18 +02:00

80 lines
2.5 KiB
Python

import os
class Path:
def __init__(self, path: str):
self.path = os.path.expanduser(path)
def exists(self) -> bool:
return os.path.exists(self.path)
def is_file(self) -> bool:
return os.path.isfile(self.path)
def is_dir(self) -> bool:
return os.path.isdir(self.path)
def read(self) -> str:
with open(self.path, 'r') as f:
return f.read()
def write(self, content: str):
os.makedirs(os.path.dirname(self.path), exist_ok=True)
with open(self.path, 'w') as f:
f.write(content)
def delete(self):
if self.is_file():
os.remove(self.path)
elif self.is_dir():
os.rmdir(self.path)
def list(self, recursive: bool = False, regex: list = None) -> list[str]:
files = []
if self.is_dir():
if recursive:
for root, _, filenames in os.walk(self.path):
for filename in filenames:
full_path = os.path.join(root, filename)
relative_path = os.path.relpath(full_path, self.path)
if regex:
import re
if any(re.match(r, relative_path) for r in regex):
files.append(relative_path)
else:
files.append(relative_path)
else:
for entry in os.listdir(self.path):
full_path = os.path.join(self.path, entry)
if os.path.isfile(full_path):
if regex:
import re
if any(re.match(r, entry) for r in regex):
files.append(entry)
else:
files.append(entry)
return files
def get(path: str) -> Path:
return Path(path)
def get_dir(path: str, create: bool = False) -> Path:
p = Path(path)
if create and not p.exists():
os.makedirs(p.path, exist_ok=True)
return p
def get_file(path: str, create: bool = False) -> Path:
p = Path(path)
if create and not p.exists():
os.makedirs(os.path.dirname(p.path), exist_ok=True)
with open(p.path, 'w') as f:
pass # Create empty file
return p
def rmdir_all(path: str):
if os.path.exists(path):
import shutil
shutil.rmtree(path)
def ls(path: str) -> list[str]:
return os.listdir(path)