import os import errno from os.path import abspath, dirname, join as pjoin def check_path(path, create=False, write=True): """Check if given path exists and is readable as well as writable if specified; if create is true and the path doesn't exist, the directories will be created if possible""" path = os.path.expanduser(path) exist = os.path.isdir(path) if not exist and create: print("Directory '%s' does not exist, it will be created now" % path) # try to create the directory; if it should exist for whatever reason, # ignore it, otherwise report the error try: os.makedirs(path) except OSError as exception: if exception.errno == errno.EACCES: print_error("[ERROR] You don't have the permission to create directories in '%s'" % dirname(path)) return False elif exception.errno != errno.EEXIST: raise return True elif not exist: print_error("[ERROR] Directory '%s' does not exist" % path) return False else: if not is_readable(path): print_error("[ERROR] Directory '%s' is not readable" % path) return False if write and not is_writable(path): print_error("[ERROR] Directory '%s' is not writable" % path) return False return True def check_file(path, file): """Check if a file in a certain path exists and is readable; if the file argument is omitted only path is checked, it's recommended to use check_path instead for this case""" path = os.path.expanduser(path) if file is None: if not os.path.isfile(path): print_error("[ERROR] The file '%s' does not exist!" % (path)) return False else: if not is_readable(path): print_error("[ERROR] The file '%s' is not readable!" % (path)) return False return True path = get_path(path, file) if not os.path.isfile(path): print_error("[ERROR] The file '%s' does not exist!" % path) return False else: if not is_readable(path): print_error("[ERROR] The file '%s' is not readable!" % (path)) return False return True def check_permission(path, permission): """Check if the given permission is allowed for path""" if os.path.exists(path): return os.access(path, permission) else: return False def is_readable(path): """Check if path is readable""" return check_permission(path, os.R_OK) def is_writable(path): """Check if path is writable""" return check_permission(path, os.W_OK) def is_executable(path): """Check if path is executable""" return check_permission(path, os.X_OK) def get_path(path, file=None): """Get the absolute path of a given path and an optional file""" if not file: return abspath(os.path.expanduser(path)) return abspath(os.path.expanduser(pjoin(path, file)))