X-Git-Url: https://wannabe.guru.org/gitweb/?a=blobdiff_plain;f=file_utils.py;h=cd37f3069c70efd5c0f835e3362adbdf18d52e24;hb=679b41526d9327f5bcecc702a928a72b68a1e0c8;hp=5d9a0be3b272bbc51eebf7894baac7a25fe11179;hpb=a0c6b6c28214e0f5167bc25690ada5d83d933086;p=python_utils.git diff --git a/file_utils.py b/file_utils.py index 5d9a0be..cd37f30 100644 --- a/file_utils.py +++ b/file_utils.py @@ -9,6 +9,7 @@ import logging import os import io import pathlib +import re import time from typing import Optional import glob @@ -20,6 +21,37 @@ from uuid import uuid4 logger = logging.getLogger(__name__) +def remove_newlines(x): + return x.replace('\n', '') + + +def strip_whitespace(x): + return x.strip() + + +def remove_hash_comments(x): + return re.sub(r'#.*$', '', x) + + +def slurp_file( + filename: str, + *, + skip_blank_lines=False, + line_transformers=[], +): + ret = [] + if not file_is_readable(filename): + raise Exception(f'{filename} can\'t be read.') + with open(filename) as rf: + for line in rf: + for transformation in line_transformers: + line = transformation(line) + if skip_blank_lines and line == '': + continue + ret.append(line) + return ret + + def remove(path: str) -> None: """Deletes a file. Raises if path refers to a directory or a file that doesn't exist. @@ -184,6 +216,18 @@ def does_file_exist(filename: str) -> bool: return os.path.exists(filename) and os.path.isfile(filename) +def file_is_readable(filename: str) -> bool: + return does_file_exist(filename) and os.access(filename, os.R_OK) + + +def file_is_writable(filename: str) -> bool: + return does_file_exist(filename) and os.access(filename, os.W_OK) + + +def file_is_executable(filename: str) -> bool: + return does_file_exist(filename) and os.access(filename, os.X_OK) + + def does_directory_exist(dirname: str) -> bool: """Returns True if a file exists and is a directory.