Source code for citelang.utils.fileio

__author__ = "Vanessa Sochat"
__copyright__ = "Copyright 2022, Vanessa Sochat"
__license__ = "MPL 2.0"

import contextlib
import errno
import json
import os
import stat
import sys
import tempfile

import yaml


[docs]def mkdir_p(path): """mkdir_p attempts to get the same functionality as mkdir -p :param path: the path to create. """ try: os.makedirs(path) except OSError as e: if e.errno == errno.EEXIST and os.path.isdir(path): pass else: sys.exit("Error creating path %s, exiting." % path)
[docs]@contextlib.contextmanager def workdir(dirname): """ Do something in the context of a directory, and then change back """ here = os.getcwd() os.chdir(dirname) yield here os.chdir(here)
[docs]def write_file(content, filename, mode="w", exec=False): """ Write content to a filename """ with open(filename, mode) as filey: filey.writelines(content) if exec: st = os.stat(filename) os.chmod(filename, st.st_mode | stat.S_IEXEC) return filename
[docs]def write_json(json_obj, filename, mode="w"): """ Write json to a filename """ with open(filename, mode) as filey: filey.writelines(print_json(json_obj)) return filename
[docs]def read_file(filename, mode="r"): """ Read a file. """ with open(filename, mode) as filey: content = filey.read() return content
[docs]def read_json(filename, mode="r"): """ Read a json file to a dictionary. """ return json.loads(read_file(filename))
[docs]def read_yaml(filename): """ Read yaml from file using the safe loader. """ with open(filename, "r") as fd: content = yaml.load(fd.read(), Loader=yaml.SafeLoader) return content
[docs]def get_tmpfile(tmpdir=None, prefix=""): """ Get a temporary file with an optional prefix. """ # First priority for the base goes to the user requested. tmpdir = get_tmpdir(tmpdir) # If tmpdir is set, add to prefix if tmpdir: prefix = os.path.join(tmpdir, os.path.basename(prefix)) fd, tmp_file = tempfile.mkstemp(prefix=prefix) os.close(fd) return tmp_file
[docs]def get_tmpdir(tmpdir=None, prefix="", create=True): """ Get a temporary directory for an operation. """ tmpdir = tmpdir or tempfile.gettempdir() prefix = prefix or "citelang-tmp" prefix = "%s.%s" % (prefix, next(tempfile._get_candidate_names())) tmpdir = os.path.join(tmpdir, prefix) if not os.path.exists(tmpdir) and create is True: os.mkdir(tmpdir) return tmpdir