Tools For Files (If Exists, Make And Delete)
323296
def file(operation, path):
    
    operation = operation.lower()
    if operation == 'exists':
        return bool(os.path.isfile(path))
    if operation == 'read':
        with open(path, 'r') as f:
            return [line.strip() for line in f]
    elif operation == 'delete':
        os.remove(path)
    elif operation == 'create':
        open(path, 'w').close()
    elif operation == 'clear':
        open(path, 'w').close()
    else:
        raise ValueError('Invalid operation provided.')
823987
def checkfiles(args):
  """"""

  from .query import Database
  db = Database()

  r = db.objects()

  # go through all files, check if they are available on the filesystem
  good = []
  bad = []
  for f in r:
    if os.path.exists(f.make_path(args.directory, args.extension)):
      good.append(f)
    else:
      bad.append(f)

  # report
  output = sys.stdout
  if args.selftest:
    from bob.db.utils import null
    output = null()

  if bad:
    for f in bad:
      output.write('Cannot find file "%s"\n' % (f.make_path(args.directory, args.extension),))
    output.write('%d files (out of %d) were not found at "%s"\n' % \
      (len(bad), len(r), args.directory))

  return 0
606191
def changes(self):
        """"""
        deleted = []
        for path in list(self.files):
            isdir = path.endswith(os.sep)
            abspath = os.path.join(self.path, path)
            try:
                is_deleted = (
                    not os.path.exists(abspath) or  # actually deleted
                    os.path.isdir(abspath) != isdir  # changed from / to folder
                )
            except EnvironmentError:
                # file is basically inaccessible at this point so we're gonna
                # assume that it was deleted
                is_deleted = True

            if is_deleted:
                deleted.append(path)
                del self.files[path]

        changed = []
        for folder, subfolders, subfiles in os.walk(self.path):
            for path in subfolders:
                path = os.path.join(folder, path)
                path = os.path.normcase(os.path.relpath(path, self.path))
                path += os.sep
                if path not in self.files:
                    # don't really care about folder mtime
                    self.files[path] = 0
                    changed.append(path)

            for path in subfiles:
                actual_path = path = os.path.join(folder, path)
                path = os.path.normcase(os.path.relpath(path, self.path))
                try:
                    mtime = os.path.getmtime(actual_path)
                    if path not in self.files:
                        # new file; set its mtime to 0 because it will be
                        # compared in the next few lines
                        self.files[path] = 0

                    if mtime > self.files[path]:
                        # file has been changed since last check
                        self.files[path] = mtime
                        changed.append(path)
                except EnvironmentError:
                    # in 99% of the cases the file has been deleted while
                    # iterating the parent folder; if the file was previously
                    # being handled, then stop handling it; otherwise ignore
                    if path in self.files:
                        deleted.append(path)
                        del self.files[path]

        self.updated = False
        return changed, deleted
787304
def gen_files(path, prefix="_"):
    "  "

    if op.isdir(path):
        for name in listdir(path):
            fpath = op.join(path, name)
            if is_parsed_file(fpath):
                yield op.abspath(fpath)

    elif is_parsed_file(path):
        yield op.abspath(path)
696147
def delete_if_exists(file)
      # Windows cannot delete open files, but we only have a path at this point
      # so it's too late to close the file. report failure to delete files but
      # otherwise continue without failing test.
      begin
        File.delete(file) if File.file?(file)
      rescue Exception => e
        puts "\nWARNING: #{e.message}"
      end
    end
885607
def cleanup(dest, tardir, counterfile):
    """"""
    thefiles = Queue()
    # dest directory files
    queue_files(dest, thefiles)
    # tar directory files
    queue_files(tardir, thefiles)
    while not thefiles.empty():
        d_file = thefiles.get()
        info("Deleting file: %s" % d_file)
        os.unlink(d_file)
    if os.path.exists(counterfile):
        info("Deleting the counter file %s" % counterfile)
        os.unlink(counterfile)
714189
def _check_file_existence(self, files):
        ''''''
        for f in files:
            if not os.path.isfile(f):
                logging.error("The file '%s' does not appear to exist, stopping" % f)
                exit(1)
893055
def get_tools(self) -> list:
        """"""
        tools = "flake8,pylint,vulture,pyroma,isort,yapf,safety,dodgy,pytest,pypi".split(
            ",")
        print("Available tools: {0}".format(",".join(tools)))
        answer = ask_list("What tools would you like to use?",
                          ["flake8", "pytest"])

        if any(tool not in tools for tool in answer):
            print("Invalid answer, retry.")
            self.get_tools()
        return answer
505945
def ensure_dirs(filename):
    """"""
    dirname, _ = os.path.split(filename)
    if dirname and not os.path.exists(dirname):
        os.makedirs(dirname)
445159
def file_exists?(paths, file)
      paths.any? do |path|
        Find.find(path)
            .map { |path_file| Shellwords.escape(path_file) }
            .include?(file)
      end
    end
1277151
def file_complete(self, prefix, args):
        
        path = os.path.expanduser(prefix)
        dirname, name = os.path.split(path)
        if not dirname:
            dirname = '.'
        try:
            dirs = os.listdir(dirname)
        except FileNotFoundError:
            return frozenset()
        choices = []
        session = self.calling_command.session
        for f in dirs:
            try:
                if (not name or f.startswith(name)) and \
                   not f.startswith('.'):
                    choices.append(f)
            except PermissionError:
                pass
        prevent_pad = session.pad_completion and len(choices) == 1 and \
            os.path.isdir(choices[0])
        names = [os.path.join(dirname, x) for x in choices]
        if prevent_pad:
            names.append(names[0] + '/')
        return frozenset(names)
1105895
def _clean_file(self, filename):
        """"""
        if not os.path.exists(filename):
            return
        self.announce("removing '{}'".format(filename))
        if not self.dry_run:
            os.remove(filename)
146302
def do_file(self, line):
        """"""
        opts = self.FILE_OPTS

        if not self.all_ontologies:
            self._help_nofiles()
            return

        line = line.split()

        if not line or line[0] not in opts:
            self.help_file()
            return

        if line[0] == "rename":
            self._rename_file()
        elif line[0] == "delete":
            self._delete_file()
        else:
            return
228982
def verify(self, tool):
        
        if os.path.isfile(tool['file']):
            print('Toolbox: program exists = TOK  :: ' + tool['file'])
            return True
        else:
            print('Toolbox: program exists = FAIL :: ' + tool['file'])
            return False
1344158
function remove(file, options, done) {
    if (arguments.length === 2 && 'function' === typeof options) {
        done = options;
        options = {};
    }

    if ('function' !== typeof done) {
        done = function() {};
    }

    function callfile(file, stats, done) {
        fs.unlink(file, done);
    }

    function calldir(dir, stats, files, state, done) {
        if (state === 'end') {
            if (options.empty && dir === file) {
                done();
            } else {
                if (stats.isSymbolicLink()) {
                    fs.unlink(dir, done);
                } else {
                    fs.rmdir(dir, function(er) {
                        if (er && (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM')) {
                            // try in few time, last deletion is not completely ended
                            setTimeout(function() {
                                fs.rmdir(dir, done);
                            }, 10);
                        } else {
                            done(er);
                        }
                    });
                }
            }
        } else {
            done();
        }
    }

    options = Object.assign({
        fs: fs,
        resolve: true,
        followSymlink: false
    }, options);

    _explore(file, callfile, calldir, options, done);
}
786451
def files_inspected(ext, delimiter = ',', remove = @config.working_dir)
        @path.is_a?(Array) ? @path.split(delimiter) : file_list(@path, ext, remove)
      end
1325577
def reset_files(self):
        
        confirm = self.no_confirm

        path = SavepathParser.get_base_path(
            SavepathParser.get_abs_path_static(
                self.cfg.section("Files")["local_data_directory"],
                os.path.dirname(self.cfg_file_path)
            )
        )

        print("""
Cleanup files:
    This will delete {path} and all its contents.
""".format(path=path))

        if not confirm:
            confirm = 'yes' in builtins.input(
                """
    Do you really want to do this? Write 'yes' to confirm: {yes}"""
                    .format(yes='yes' if confirm else ''))

        if not confirm:
            print("Did not type yes. Thus aborting.")
            return

        print("Removing: {}".format(path))

        try:
            shutil.rmtree(path)
        except OSError as error:
            if not os.path.exists(path):
                self.log.error("%s does not exist.", path)
            self.log.error(error)