我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用os.path.endswith()。
def uninstallation_paths(dist): """ Yield all the uninstallation paths for dist based on RECORD-without-.pyc Yield paths to all the files in RECORD. For each .py file in RECORD, add the .pyc in the same directory. UninstallPathSet.add() takes care of the __pycache__ .pyc. """ from pip.utils import FakeFile # circular import r = csv.reader(FakeFile(dist.get_metadata_lines('RECORD'))) for row in r: path = os.path.join(dist.location, row[0]) yield path if path.endswith('.py'): dn, fn = os.path.split(path) base = fn[:-3] path = os.path.join(dn, base + '.pyc') yield path
def file_type(path): """ Return 'fasta' or 'fastq' depending on file format. The file may optionally be gzip-compressed. """ if path.endswith('.gz'): file = xopen(path) else: file = open(path) with file as f: first_char = f.read(1) if first_char == '@': return 'fastq' elif first_char == '>': return 'fasta' else: raise UnknownFileFormatError('Cannot recognize format. File starts with neither ">" nor "@"')
def list_children(self, path): """ Yield all direct children of the given root-relative path, as root- relative paths. If the path refers to a file, there will be no children. """ if len(path) > 0 and not path.endswith("/"): # We need a trailing slash after a real directory name for urljoin # to work later path = path + "/" # Strip leading slashes from the input path, so we always look inside # our base path. path = path.lstrip("/") # Construct the path to actually go to on the FTP server ftp_path = urlparse.urljoin(self.base_path, path) Logger.debug("Listing {}".format(ftp_path)) for child in robust_nlst(self.connection, ftp_path): # For every child, build a root-relative URL yield urlparse.urljoin(path, child)
def ignore_file(info): path = info.filename if info.file_size > 256 * 1024: return True if path.endswith('.png') or path.endswith('.jpeg') or path.endswith('.ttf') or path.endswith('.otf') or path.endswith('.gif'): return True if path.endswith('.mf') or path.endswith('.sf') or path.endswith('.rsa'): return True if path.startswith('resources/addon-sdk/'): return True if 'jquery' in path: return True if 'bootstrap' in path and 'css' in path: return True return False
def parse_ebuild_path(uri): if not path.isfile(uri) or not path.endswith('.ebuild'): return Result.Err() uri = path.abspath(uri) dirn, basen = path.split(uri) basen = basen[:-7] _, name, v1, v2, v3 = cpv_split(basen) ver = ver_str(v1, v2, v3) parent = dirn.split('/')[-1] # we need to query the impure world # TODO: write a global option which would set the impure values non-interactively if not ver: ver = query('version', 'Please specify package version for {}'.format(basen)).expect() category = query('category', 'Please enter category for {}'.format(basen), parent).expect() slot = query('slot', 'Please specify package slot', '0').expect() return Result.Ok(LocalEbuild(uri, category, name, ver, slot))
def walk_directories(root): """'find' in a generator function.""" for child in os.listdir(root): if child.startswith("."): continue full_path = path.join(root, child) if path.isfile(full_path): yield full_path elif full_path.endswith((path.sep+".", path.sep+"..")): continue elif path.islink(full_path): continue else: for fp in walk_directories(full_path): yield fp
def monkeytype_config(path: str) -> Config: """Imports the config instance specified by path. Path should be in the form module:qualname. Optionally, path may end with (), in which case we will call/instantiate the given class/function. """ should_call = False if path.endswith('()'): should_call = True path = path[:-2] module, qualname = module_path_with_qualname(path) try: config = get_name_in_module(module, qualname) except MonkeyTypeError as mte: raise argparse.ArgumentTypeError(f'cannot import {path}: {mte}') if should_call: config = config() return config
def displaySheet(self, sessionName, download=False, allUsers=False, keepHidden=False): sheet = sdproxy.getSheet(sessionName, display=True) if not sheet: self.displayMessage('Unable to retrieve sheet '+sessionName) return lastname_col, firstname_col, midname_col, id_col, email_col, altid_col = Options["roster_columns"].split(',') timestamp = '' if sessionName.endswith('-answers') or sessionName.endswith('-correct') or sessionName.endswith('-stats'): try: timestamp = sliauth.iso_date(sdproxy.lookupValues('_average', ['Timestamp'], sessionName)['Timestamp']) except Exception, excp: pass rows = sheet.export(csvFormat=download, allUsers=allUsers, keepHidden=keepHidden, idRename=id_col, altidRename=altid_col) if download: self.set_header('Content-Type', 'text/csv') self.set_header('Content-Disposition', 'attachment; filename="%s.csv"' % sessionName) self.write(rows) else: self.render('table.html', site_name=Options['site_name'], table_name=sessionName, table_data=rows, table_fixed='fixed', timestamp=timestamp)
def get_project_config_file(path, default_config_file_name): """Attempts to extract the project config file's absolute path from the given path. If the path is a directory, it automatically assumes a "config.yml" file will be in that directory. If the path is to a .yml file, it assumes that that is the root configuration file for the project.""" _path, _config_file_path = None, None path = os.path.abspath(path) if os.path.isdir(path): _path = path # use the default config file _config_file_path = os.path.join(_path, default_config_file_name) logger.debug("Using default project configuration file path: %s" % _config_file_path) elif path.endswith(".yml"): _path = os.path.dirname(path) _config_file_path = path logger.debug("Using custom project configuration file path: %s" % _config_file_path) return _path, _config_file_path
def openFileDialog( self ): settings = QSettings() path = QFileDialog.getSaveFileName( self, QApplication.translate( "ExportAutoFields", "Create a JSON file" ), settings.value( self.autoFieldManager.settingsPrefix + "/export/dir", "", type=str ), "JSON files (*.json)" ) if path: if not path.endswith( '.json' ): path += '.json' self.txtExportFile.setText( path ) settings.setValue( self.autoFieldManager.settingsPrefix + "/export/dir", os.path.dirname( path ) )
def listdir(dirpath, endswith=None): filenames = [ ] # if the specified directory exists, list its contents if os.path.isdir(dirpath): filenames += os.listdir(dirpath) # if the corresponding zip archive exists, list its contents as well zippath = dirpath + ".zip" if os.path.isfile(zippath): filenames += zipfile.ZipFile(zippath,'r').namelist() # if requested, filter the names if endswith != None: filenames = filter(lambda fn: fn.endswith(endswith), filenames) # remove duplicates and sort the list return sorted(list(set(filenames))) # -----------------------------------------------------------------