Python os.path.isfile() Examples

The following are 30 code examples of os.path.isfile(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module os.path , or try the search function .
Example #1
Source File: qr_reader.py    From Authenticator with GNU General Public License v2.0 11 votes vote down vote up
def read(self):
        try:
            from PIL import Image
            from pyzbar.pyzbar import decode
            decoded_data = decode(Image.open(self.filename))
            if path.isfile(self.filename):
                remove(self.filename)
            try:
                url = urlparse(decoded_data[0].data.decode())
                query_params = parse_qsl(url.query)
                self._codes = dict(query_params)
                return self._codes.get("secret")
            except (KeyError, IndexError):
                Logger.error("Invalid QR image")
                return None
        except ImportError:
            from ..application import Application
            Application.USE_QRSCANNER = False
            QRReader.ZBAR_FOUND = False 
Example #2
Source File: GXManufacturerCollection.py    From Gurux.DLMS.Python with GNU General Public License v2.0 7 votes vote down vote up
def isUpdatesAvailable(cls, path):
        if sys.version_info < (3, 0):
            return False
        # pylint: disable=broad-except
        if not os.path.isfile(os.path.join(path, "files.xml")):
            return True
        try:
            available = dict()
            for it in ET.parse(os.path.join(path, "files.xml")).iter():
                if it.tag == "File":
                    available[it.text] = datetime.datetime.strptime(it.attrib["Modified"], "%d-%m-%Y")

            path = NamedTemporaryFile()
            path.close()
            urllib.request.urlretrieve("https://www.gurux.fi/obis/files.xml", path.name)
            for it in ET.parse(path.name).iter():
                if it.tag == "File":
                    tmp = datetime.datetime.strptime(it.attrib["Modified"], "%d-%m-%Y")
                    if not it.text in available or available[it.text] != tmp:
                        return True
        except Exception as e:
            print(e)
            return True
        return False 
Example #3
Source File: ssh.py    From b1tifi with MIT License 7 votes vote down vote up
def ThreadSSH(self):
        try:
            self.session = pxssh.pxssh(encoding='utf-8')
            if (not path.isfile(self.settings['Password'])):
                self.session.login(gethostbyname(self.settings['Host']), self.settings['User'],
                self.settings['Password'],port=self.settings['Port'])
            else:
                self.session.login(gethostbyname(self.settings['Host']), self.settings['User'],
                ssh_key=self.settings['Password'],port=self.settings['Port'])

            if self.connection:
                self.status = '[{}]'.format(setcolor('ON',color='green'))
            self.activated = True
        except Exception, e:
            self.status = '[{}]'.format(setcolor('OFF',color='red'))
            self.activated = False 
Example #4
Source File: senna.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, senna_path, operations, encoding='utf-8'):
        self._encoding = encoding
        self._path = path.normpath(senna_path) + sep 
        
        # Verifies the existence of the executable on the self._path first    
        #senna_binary_file_1 = self.executable(self._path)
        exe_file_1 = self.executable(self._path)
        if not path.isfile(exe_file_1):
            # Check for the system environment 
            if 'SENNA' in environ:
                #self._path = path.join(environ['SENNA'],'')  
                self._path = path.normpath(environ['SENNA']) + sep 
                exe_file_2 = self.executable(self._path)
                if not path.isfile(exe_file_2):
                    raise OSError("Senna executable expected at %s or %s but not found" % (exe_file_1,exe_file_2))
        
        self.operations = operations 
Example #5
Source File: utils.py    From Att-ChemdNER with Apache License 2.0 6 votes vote down vote up
def get_perf(filename):
    ''' run conlleval.pl perl script to obtain
    precision/recall and F1 score '''
    _conlleval = PREFIX + 'conlleval'
    if not isfile(_conlleval):
        #download('http://www-etud.iro.umontreal.ca/~mesnilgr/atis/conlleval.pl') 
        os.system('wget https://www.comp.nus.edu.sg/%7Ekanmy/courses/practicalNLP_2008/packages/conlleval.pl')
        chmod('conlleval.pl', stat.S_IRWXU) # give the execute permissions
    
    out = []
    proc = subprocess.Popen(["perl", _conlleval], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    stdout, _ = proc.communicate(open(filename).read())
    for line in stdout.split('\n'):
        if 'accuracy' in line:
            out = line.split()
            break
    
    # out = ['accuracy:', '16.26%;', 'precision:', '0.00%;', 'recall:', '0.00%;', 'FB1:', '0.00']
    precision = float(out[3][:-2])
    recall    = float(out[5][:-2])
    f1score   = float(out[7])

    return {'p':precision, 'r':recall, 'f1':f1score} 
Example #6
Source File: pascal_voc.py    From mmdetection with Apache License 2.0 6 votes vote down vote up
def cvt_annotations(devkit_path, years, split, out_file):
    if not isinstance(years, list):
        years = [years]
    annotations = []
    for year in years:
        filelist = osp.join(devkit_path,
                            f'VOC{year}/ImageSets/Main/{split}.txt')
        if not osp.isfile(filelist):
            print(f'filelist does not exist: {filelist}, '
                  f'skip voc{year} {split}')
            return
        img_names = mmcv.list_from_file(filelist)
        xml_paths = [
            osp.join(devkit_path, f'VOC{year}/Annotations/{img_name}.xml')
            for img_name in img_names
        ]
        img_paths = [
            f'VOC{year}/JPEGImages/{img_name}.jpg' for img_name in img_names
        ]
        part_annotations = mmcv.track_progress(parse_xml,
                                               list(zip(xml_paths, img_paths)))
        annotations.extend(part_annotations)
    mmcv.dump(annotations, out_file)
    return annotations 
Example #7
Source File: hook.py    From linter-pylama with MIT License 6 votes vote down vote up
def install_hg(path):
    """ Install hook in Mercurial repository. """
    hook = op.join(path, 'hgrc')
    if not op.isfile(hook):
        open(hook, 'w+').close()

    c = ConfigParser()
    c.readfp(open(hook, 'r'))
    if not c.has_section('hooks'):
        c.add_section('hooks')

    if not c.has_option('hooks', 'commit'):
        c.set('hooks', 'commit', 'python:pylama.hooks.hg_hook')

    if not c.has_option('hooks', 'qrefresh'):
        c.set('hooks', 'qrefresh', 'python:pylama.hooks.hg_hook')

    c.write(open(hook, 'w+')) 
Example #8
Source File: init_pg.py    From cassh with Apache License 2.0 6 votes vote down vote up
def init_pg(pg_conn):
    """
    Initialize pg database
    """
    if pg_conn is None:
        print('I am unable to connect to the database')
        sys.exit(1)
    cur = pg_conn.cursor()

    sql_files = [f for f in listdir(SQL_SERVER_PATH) if isfile(join(SQL_SERVER_PATH, f))]

    for sql_file in sql_files:
        with open('%s/%s' % (SQL_SERVER_PATH, sql_file), 'r') as sql_model_file:
            cur.execute(sql_model_file.read())
            pg_conn.commit()

    cur.close()
    pg_conn.close() 
Example #9
Source File: process_imagenet.py    From nsf with MIT License 6 votes vote down vote up
def process_images(*, path, outfile):
    assert os.path.exists(path), "Input path doesn't exist"
    files = [f for f in listdir(path) if isfile(join(path, f))]
    print('Number of valid images is:', len(files))
    imgs = []
    for i in tqdm(range(len(files))):
        img = scipy.ndimage.imread(join(path, files[i]))

        assert isinstance(img, np.ndarray)

        img = img.astype('uint8')

        # HWC -> CHW, for use in PyTorch
        img = img.transpose(2, 0, 1)
        assert img.shape == (3, 64, 64)

        imgs.append(img)

    imgs = np.asarray(imgs).astype('uint8')
    assert imgs.shape[1:] == (3, 64, 64)

    np.save(outfile, imgs) 
Example #10
Source File: check.py    From 3vilTwinAttacker with MIT License 6 votes vote down vote up
def check_dependencies():
    ettercap = popen('which ettercap').read().split("\n")
    dhcpd = popen('which dhcpd').read().split("\n")
    lista = [dhcpd[0],'/usr/sbin/airbase-ng',
    ettercap[0]]
    m = []
    for i in lista:
        m.append(path.isfile(i))
    for k,g in enumerate(m):
        if m[k] == False:
            if k == 0:
                print '[%s✘%s] DHCP not %sfound%s.'%(RED,ENDC,YELLOW,ENDC)
    for c in m:
        if c == False:
            exit(1)
        break 
Example #11
Source File: movie_recommender.py    From Data_Analytics_with_Hadoop with MIT License 6 votes vote down vote up
def load_ratings(file, sep='\t'):
    """
    Load ratings from file
    """
    if not isfile(file):
        print "File %s does not exist." % file
        sys.exit(1)
    f = open(file, 'r')
    # Filter based on movie ratings that have been seen (0 = not seen)
    ratings = filter(lambda r: r[2] > 0, [parse_rating(line, '\t')[1] for line in f])
    f.close()
    if not ratings:
        print "No ratings provided."
        sys.exit(1)
    else:
        return ratings 
Example #12
Source File: GXManufacturerCollection.py    From Gurux.DLMS.Python with GNU General Public License v2.0 6 votes vote down vote up
def readManufacturerSettings(cls, manufacturers, path):
        # pylint: disable=broad-except
        manufacturers = []
        files = [f for f in listdir(path) if isfile(join(path, f))]
        if files:
            for it in files:
                if it.endswith(".obx"):
                    try:
                        manufacturers.append(cls.__parse(os.path.join(path, it)))
                    except Exception as e:
                        print(e)
                        continue

    #
    # Serialize manufacturer from the xml.
    #
    # @param in
    #            Input stream.
    # Serialized manufacturer.
    # 
Example #13
Source File: imdb_pytorch.py    From lineflow with MIT License 6 votes vote down vote up
def build_vocab(tokens, cache='vocab.pkl', max_size=50000):
    if not osp.isfile(cache):
        counter = Counter(tokens)
        words, _ = zip(*counter.most_common(max_size))
        words = [PAD_TOKEN, UNK_TOKEN] + list(words)
        token_to_index = dict(zip(words, range(len(words))))
        if START_TOKEN not in token_to_index:
            token_to_index[START_TOKEN] = len(token_to_index)
            words += [START_TOKEN]
        if END_TOKEN not in token_to_index:
            token_to_index[END_TOKEN] = len(token_to_index)
            words += [END_TOKEN]
        with open(cache, 'wb') as f:
            pickle.dump((token_to_index, words), f)
    else:
        with open(cache, 'rb') as f:
            token_to_index, words = pickle.load(f)

    return token_to_index, words 
Example #14
Source File: __init__.py    From aws-ops-automator with Apache License 2.0 6 votes vote down vote up
def all_services():
    """
    Return as list of all supported service names
    :return: list of all supported service names
    """
    result = []
    for f in listdir(SERVICES_PATH):
        if isfile(join(SERVICES_PATH, f)) and f.endswith("_{}.py".format(SERVICE.lower())):
            module_name = SERVICE_MODULE_NAME.format(f[0:-len(".py")])
            service_module = _get_module(module_name)
            cls = _get_service_class(service_module)
            if cls is not None:
                service_name = cls[0][0:-len(SERVICE)]
                if service_name.lower() != "aws":
                    result.append(service_name)
    return result 
Example #15
Source File: toolchain.py    From calmjs with GNU General Public License v2.0 6 votes vote down vote up
def compile_bundle_entry(self, spec, entry):
        """
        Handler for each entry for the bundle method of the compile
        process.  This copies the source file or directory into the
        build directory.
        """

        modname, source, target, modpath = entry
        bundled_modpath = {modname: modpath}
        bundled_target = {modname: target}
        export_module_name = []
        if isfile(source):
            export_module_name.append(modname)
            copy_target = join(spec[BUILD_DIR], target)
            if not exists(dirname(copy_target)):
                makedirs(dirname(copy_target))
            shutil.copy(source, copy_target)
        elif isdir(source):
            copy_target = join(spec[BUILD_DIR], modname)
            shutil.copytree(source, copy_target)

        return bundled_modpath, bundled_target, export_module_name 
Example #16
Source File: pascal_voc.py    From AerialDetection with Apache License 2.0 6 votes vote down vote up
def cvt_annotations(devkit_path, years, split, out_file):
    if not isinstance(years, list):
        years = [years]
    annotations = []
    for year in years:
        filelist = osp.join(devkit_path, 'VOC{}/ImageSets/Main/{}.txt'.format(
            year, split))
        if not osp.isfile(filelist):
            print('filelist does not exist: {}, skip voc{} {}'.format(
                filelist, year, split))
            return
        img_names = mmcv.list_from_file(filelist)
        xml_paths = [
            osp.join(devkit_path, 'VOC{}/Annotations/{}.xml'.format(
                year, img_name)) for img_name in img_names
        ]
        img_paths = [
            'VOC{}/JPEGImages/{}.jpg'.format(year, img_name)
            for img_name in img_names
        ]
        part_annotations = mmcv.track_progress(parse_xml,
                                               list(zip(xml_paths, img_paths)))
        annotations.extend(part_annotations)
    mmcv.dump(annotations, out_file)
    return annotations 
Example #17
Source File: __init__.py    From aws-ops-automator with Apache License 2.0 6 votes vote down vote up
def all_actions():
    """
    Returns a list of all available actions from the *.py files in the actions directory
    :return: ist of all available action
    """
    result = []
    directory = os.getcwd()
    while True:
        if any([entry for entry in listdir(directory) if entry == ACTIONS_DIR and isdir(os.path.join(directory, entry))]):
            break
        directory = os.path.abspath(os.path.join(directory, '..'))

    actions_dir = os.path.join(directory, ACTIONS_DIR)
    for f in listdir(actions_dir):
        if isfile(join(actions_dir, f)) and f.endswith("_{}.py".format(ACTION.lower())):
            module_name = ACTION_MODULE_NAME.format(f[0:-len(".py")])
            mod = get_action_module(module_name)
            cls = _get_action_class_from_module(mod)
            if cls is not None:
                action_name = cls[0][0:-len(ACTION)]
                result.append(action_name)
    return result 
Example #18
Source File: __init__.py    From aws-ops-automator with Apache License 2.0 6 votes vote down vote up
def all_handlers():
    global __actions
    if __actions is None:
        __actions = []
        current = abspath(os.getcwd())
        while True:
            if isdir(os.path.join(current, "handlers")):
                break
            parent = dirname(current)
            if parent == current:
                # at top level
                raise Exception("Could not find handlers directory")
            else:
                current = parent

        for f in listdir(os.path.join(current, "handlers")):
            if isfile(join(current, "handlers", f)) and f.endswith("_{}.py".format(HANDLER.lower())):
                module_name = HANDLERS_MODULE_NAME.format(f[0:-len(".py")])
                m = _get_module(module_name)
                cls = _get_handler_class(m)
                if cls is not None:
                    handler_name = cls[0]
                    __actions.append(handler_name)
    return __actions 
Example #19
Source File: cloud_connect_mod_input.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _load_options_from_inputs_spec(app_root, stanza_name):
    input_spec_file = 'inputs.conf.spec'
    file_path = op.join(app_root, 'README', input_spec_file)

    if not op.isfile(file_path):
        raise RuntimeError("README/%s doesn't exist" % input_spec_file)

    parser = configparser.RawConfigParser(allow_no_value=True)
    parser.read(file_path)
    options = list(parser.defaults().keys())
    stanza_prefix = '%s://' % stanza_name

    stanza_exist = False
    for section in parser.sections():
        if section == stanza_name or section.startswith(stanza_prefix):
            options.extend(parser.options(section))
            stanza_exist = True
    if not stanza_exist:
        raise RuntimeError("Stanza %s doesn't exist" % stanza_name)
    return set(options) 
Example #20
Source File: cloud_connect_mod_input.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _load_options_from_inputs_spec(app_root, stanza_name):
    input_spec_file = 'inputs.conf.spec'
    file_path = op.join(app_root, 'README', input_spec_file)

    if not op.isfile(file_path):
        raise RuntimeError("README/%s doesn't exist" % input_spec_file)

    parser = configparser.RawConfigParser(allow_no_value=True)
    parser.read(file_path)
    options = list(parser.defaults().keys())
    stanza_prefix = '%s://' % stanza_name

    stanza_exist = False
    for section in parser.sections():
        if section == stanza_name or section.startswith(stanza_prefix):
            options.extend(parser.options(section))
            stanza_exist = True
    if not stanza_exist:
        raise RuntimeError("Stanza %s doesn't exist" % stanza_name)
    return set(options) 
Example #21
Source File: prepare.py    From MySQL-AutoXtraBackup with MIT License 6 votes vote down vote up
def parse_backup_tags(backup_dir, tag_name):
        """
        Static Method for returning the backup directory name and backup type
        :param backup_dir: The backup directory path
        :param tag_name: The tag name to search
        :return: Tuple of (backup directory, backup type) (2017-11-09_19-37-16, Full).
        :raises: RuntimeError if there is no such tag inside backup_tags.txt
        """
        if os.path.isfile("{}/backup_tags.txt".format(backup_dir)):
            with open('{}/backup_tags.txt'.format(backup_dir), 'r') as bcktags:
                f = bcktags.readlines()

            for i in f:
                splitted = i.split('\t')
                if tag_name == splitted[-1].rstrip("'\n\r").lstrip("'"):
                    return splitted[0], splitted[1]
            raise RuntimeError('There is no such tag for backups') 
Example #22
Source File: backuper.py    From MySQL-AutoXtraBackup with MIT License 6 votes vote down vote up
def show_tags(backup_dir):
        if os.path.isfile("{}/backup_tags.txt".format(backup_dir)):
            with open('{}/backup_tags.txt'.format(backup_dir), 'r') as bcktags:
                from_file = bcktags.read()
            column_names = "{0}\t{1}\t{2}\t{3}\t{4}\tTAG\n".format(
                "Backup".ljust(19),
                "Type".ljust(4),
                "Status".ljust(2),
                "Completion_time".ljust(19),
                "Size")
            extra_str = "{}\n".format("-"*(len(column_names)+21))
            print(column_names + extra_str + from_file)
            logger.info(column_names + extra_str + from_file)
        else:
            logger.warning("Could not find backup_tags.txt inside given backup directory. Can't print tags.")
            print("WARNING: Could not find backup_tags.txt inside given backup directory. Can't print tags.") 
Example #23
Source File: seq2seq_pytorch.py    From lineflow with MIT License 6 votes vote down vote up
def build_vocab(tokens, cache='vocab.pkl', max_size=50000):
    if not osp.isfile(cache):
        counter = Counter(tokens)
        words, _ = zip(*counter.most_common(max_size))
        words = [PAD_TOKEN, UNK_TOKEN] + list(words)
        token_to_index = dict(zip(words, range(len(words))))
        if START_TOKEN not in token_to_index:
            token_to_index[START_TOKEN] = len(token_to_index)
            words += [START_TOKEN]
        if END_TOKEN not in token_to_index:
            token_to_index[END_TOKEN] = len(token_to_index)
            words += [END_TOKEN]
        with open(cache, 'wb') as f:
            pickle.dump((token_to_index, words), f)
    else:
        with open(cache, 'rb') as f:
            token_to_index, words = pickle.load(f)

    return token_to_index, words 
Example #24
Source File: template.py    From landmarkerio-server with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def convert_legacy_template(path):
    with open(path) as f:
        ta = f.read().strip().split('\n\n')

    groups = [parse_group(g) for g in ta]
    data = {'groups': [group_to_dict(g) for g in groups]}

    new_path = path[:-3] + 'yml'
    warning = ''
    if p.isfile(new_path):
        new_path = path[:-4] + '-converted.yml'
        warning = '(appended -converted to avoid collision)'

    with open(new_path, 'w') as nf:
        yaml.dump(data, nf, indent=4,  default_flow_style=False)

    os.remove(path)

    print " - {} > {} {}".format(path, new_path, warning) 
Example #25
Source File: GXManufacturerCollection.py    From Gurux.DLMS.Python with GNU General Public License v2.0 5 votes vote down vote up
def isFirstRun(cls, path):
        if not os.path.isdir(path):
            os.mkdir(path)
            return True
        if not os.path.isfile(os.path.join(path, "files.xml")):
            return True
        return False

    #
    # Check if there are any updates available in Gurux www server.
    #
    # @param path
    #            Settings directory.
    # Returns true if there are any updates available.
    # 
Example #26
Source File: setup.py    From sslyze with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_include_files() -> List[Tuple[str, str]]:
    """"Get the list of trust stores so they properly packaged when doing a cx_freeze build.
    """
    plugin_data_files = []
    trust_stores_pem_path = root_path / "sslyze" / "plugins" / "certificate_info" / "trust_stores" / "pem_files"
    for file in listdir(trust_stores_pem_path):
        file = path.join(trust_stores_pem_path, file)
        if path.isfile(file):  # skip directories
            filename = path.basename(file)
            plugin_data_files.append((file, path.join("pem_files", filename)))
    return plugin_data_files 
Example #27
Source File: helper.py    From hsds with Apache License 2.0 5 votes vote down vote up
def getHDF5JSON(filename):
    if not op.isfile(filename):
        return None
    hdf5_json = None
    with open(filename) as f:
        hdf5_json = json.load(f)
    return hdf5_json 
Example #28
Source File: dataset.py    From Dispersion-based-Clustering with MIT License 5 votes vote down vote up
def _check_integrity(self):
        return osp.isdir(osp.join(self.root, 'images')) and \
               osp.isfile(osp.join(self.root, 'meta.json')) and \
               osp.isfile(osp.join(self.root, 'splits.json')) 
Example #29
Source File: mjsynth_charnet.py    From reading-text-in-the-wild with GNU General Public License v3.0 5 votes vote down vote up
def loadImage(self, filename):
        if not isfile(filename):
            print filename + "does not exist"
        else:
            img = mpimg.imread(filename)
            if len(img.shape) == 3 and img.shape[2] == 3:
                img = np.dot(img[...,:3], [0.2989, 0.5870, 0.1140]) # Convert to greyscale
            im = resize(img, (32,100), order=1, preserve_range=True)
            im = np.array(im,dtype=np.float32) # convert to single precision
            img = (im - np.mean(im)) / ( (np.std(im) + 0.0001) )

            return img 
Example #30
Source File: neural_network.py    From CalibrationNN with GNU General Public License v3.0 5 votes vote down vote up
def __fromfile(self):
        file_name = self.file_name() + '.h5'
        if isfile(file_name):
            self.model = load_model(file_name)
        else:
            self.model = None