Python glob 模块,glob1() 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用glob.glob1()。
def index(tagname):
"""Return the name of the submodule that tagname is defined in,
as well as a list of modules and keys in which this tagname is used."""
mods = glob.glob1(__path__[0], '*.py')
keys = []
usedin = {}
for m in mods:
if m[:2] == '__':
continue
modname = __name__ + '.' + m[:-3]
path = string.split(modname, '.')
module = __import__(modname)
# find the deepest submodule
for modname in path[1:]:
module = getattr(module, modname)
if hasattr(module, 'content'):
c = module.content
for k in c.keys():
if k == tagname:
keys.append(m)
for item in c[k]:
if string.find(item, tagname) != -1:
usedin[(m, k)] = 1
return keys, usedin.keys()
def logit(message):
line = "["+ time.strftime("%d.%m.%Y %H:%M:%S") +"] "+ message
print line
if Logging:
if get_filesize(Logfile) >= MAXLOGSIZE:
if LOGROTATE:
print "["+ time.strftime("%d.%m.%Y %H:%M:%S") +"] Rotating Logfile"
file_count = len(glob.glob1(os.path.dirname(Logfile), os.path.basename(Logfile)+"*"))
new_file_count = (file_count + 1)
if file_count == 1:
extension = ".1"
elif file_count > 1:
extension = "."+ str(new_file_count)
os.rename(Logfile, Logfile + extension)
else:
os.remove(Logfile)
with open(Logfile, 'a') as f:
f.write(line +"\n")
def get_info_from_updates_folder(files_list=False):
updates_dir = '{0}/updates'.format(env_mode.get_current_path())
json_files = glob.glob1(updates_dir, '*.json')
if files_list:
return json_files
updates_list = []
for jf in json_files:
if jf != 'versions.json':
print '{0}/{1}'.format(updates_dir, jf)
updates_list.append(read_json_from_path('{0}/{1}'.format(updates_dir, jf)))
return updates_list
def _list_cache_files(self):
"""
Get a list of paths to all the cache files. These are all the files
in the root cache dir that end on the cache_suffix.
"""
if not os.path.exists(self._dir):
return []
filelist = [os.path.join(self._dir, fname) for fname
in glob.glob1(self._dir, '*%s' % self.cache_suffix)]
return filelist
def _list_cache_files(self):
"""
Get a list of paths to all the cache files. These are all the files
in the root cache dir that end on the cache_suffix.
"""
if not os.path.exists(self._dir):
return []
filelist = [os.path.join(self._dir, fname) for fname
in glob.glob1(self._dir, '*%s' % self.cache_suffix)]
return filelist
def _list_cache_files(self):
"""
Get a list of paths to all the cache files. These are all the files
in the root cache dir that end on the cache_suffix.
"""
if not os.path.exists(self._dir):
return []
filelist = [os.path.join(self._dir, fname) for fname
in glob.glob1(self._dir, '*%s' % self.cache_suffix)]
return filelist
def _list_cache_files(self):
"""
Get a list of paths to all the cache files. These are all the files
in the root cache dir that end on the cache_suffix.
"""
if not os.path.exists(self._dir):
return []
filelist = [os.path.join(self._dir, fname) for fname
in glob.glob1(self._dir, '*%s' % self.cache_suffix)]
return filelist
def _list_cache_files(self):
"""
Get a list of paths to all the cache files. These are all the files
in the root cache dir that end on the cache_suffix.
"""
if not os.path.exists(self._dir):
return []
filelist = [os.path.join(self._dir, fname) for fname
in glob.glob1(self._dir, '*%s' % self.cache_suffix)]
return filelist
def _list_cache_files(self):
"""
Get a list of paths to all the cache files. These are all the files
in the root cache dir that end on the cache_suffix.
"""
if not os.path.exists(self._dir):
return []
filelist = [os.path.join(self._dir, fname) for fname
in glob.glob1(self._dir, '*%s' % self.cache_suffix)]
return filelist
def glob(self, pattern, exclude = None):
"""Add a list of files to the current component as specified in the
glob pattern. Individual files can be excluded in the exclude list."""
files = glob.glob1(self.absolute, pattern)
for f in files:
if exclude and f in exclude: continue
self.add_file(f)
return files
def glob(self, pattern, exclude = None):
"""Add a list of files to the current component as specified in the
glob pattern. Individual files can be excluded in the exclude list."""
files = glob.glob1(self.absolute, pattern)
for f in files:
if exclude and f in exclude: continue
self.add_file(f)
return files
def build_pdbzip():
pdbexclude = ['kill_python.pdb', 'make_buildinfo.pdb',
'make_versioninfo.pdb']
path = "python-%s%s-pdb.zip" % (full_current_version, msilib.arch_ext)
pdbzip = zipfile.ZipFile(path, 'w')
for f in glob.glob1(os.path.join(srcdir, PCBUILD), "*.pdb"):
if f not in pdbexclude and not f.endswith('_d.pdb'):
pdbzip.write(os.path.join(srcdir, PCBUILD, f), f)
pdbzip.close()
def glob(self, pattern, exclude = None):
"""Add a list of files to the current component as specified in the
glob pattern. Individual files can be excluded in the exclude list."""
files = glob.glob1(self.absolute, pattern)
for f in files:
if exclude and f in exclude: continue
self.add_file(f)
return files
def glob(self, pattern, exclude = None):
"""Add a list of files to the current component as specified in the
glob pattern. Individual files can be excluded in the exclude list."""
files = glob.glob1(self.absolute, pattern)
for f in files:
if exclude and f in exclude: continue
self.add_file(f)
return files
def build_pdbzip():
pdbexclude = ['kill_python.pdb', 'make_buildinfo.pdb',
'make_versioninfo.pdb']
path = "python-%s%s-pdb.zip" % (full_current_version, msilib.arch_ext)
pdbzip = zipfile.ZipFile(path, 'w')
for f in glob.glob1(os.path.join(srcdir, PCBUILD), "*.pdb"):
if f not in pdbexclude and not f.endswith('_d.pdb'):
pdbzip.write(os.path.join(srcdir, PCBUILD, f), f)
pdbzip.close()
def __resume_from_dir__(self, dir):
# setup working directory
working_dir = os.path.realpath(dir)
self.timestamp = os.path.basename(working_dir)
# Set up result folder structure
results_path = "{}/results".format(working_dir, self.timestamp)
# Set up tensorboard directory
tensorboard = "{}/tensorboard".format(working_dir, self.timestamp)
# set path to kill file (if this file exists abort run)
kill_file_name = "ABORT_RUN"
kill_file = os.path.join(working_dir, kill_file_name)
if os.path.exists(kill_file):
os.remove(kill_file)
# create plot file to plot by default
plot_file_name = "PLOT_ON"
plot_file = os.path.join(working_dir, plot_file_name)
if not (os.path.exists(results_path) or not os.path.exists(tensorboard)):
raise Exception("can not resume from given directory")
checkpoints = glob.glob1(results_path, "*.ckpt*")
checkpoints = [checkpoint for checkpoint in checkpoints if
not (".meta" in checkpoint or ".index" in checkpoint)]
checkpoints = natsorted(checkpoints)
checkpoint = os.path.join(results_path, checkpoints[-1])
if not os.path.exists(checkpoint):
raise Exception("could not find checkpoint in given directory")
if not checkpoint.endswith("ckpt"):
checkpoint = checkpoint[:checkpoint.index(".ckpt.") + 5]
return [working_dir, results_path, tensorboard, kill_file, plot_file, checkpoint]
def _list_cache_files(self):
"""
Get a list of paths to all the cache files. These are all the files
in the root cache dir that end on the cache_suffix.
"""
if not os.path.exists(self._dir):
return []
filelist = [os.path.join(self._dir, fname) for fname
in glob.glob1(self._dir, '*%s' % self.cache_suffix)]
return filelist
def _list_cache_files(self):
"""
Get a list of paths to all the cache files. These are all the files
in the root cache dir that end on the cache_suffix.
"""
if not os.path.exists(self._dir):
return []
filelist = [os.path.join(self._dir, fname) for fname
in glob.glob1(self._dir, '*%s' % self.cache_suffix)]
return filelist
def _list_cache_files(self):
"""
Get a list of paths to all the cache files. These are all the files
in the root cache dir that end on the cache_suffix.
"""
if not os.path.exists(self._dir):
return []
filelist = [os.path.join(self._dir, fname) for fname
in glob.glob1(self._dir, '*%s' % self.cache_suffix)]
return filelist
def send_cat(bot, update, user_data):
cat_list = glob1("cats", "*.jp*g")
cat_pic = os.path.join('cats', random.choice(cat_list))
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=open(cat_pic, 'rb'))
def send_cat(bot, update, user_data):
cat_list = glob1("cats", "*.jp*g")
cat_pic = os.path.join('cats', random.choice(cat_list))
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=open(cat_pic, 'rb'))
def send_cat(bot, update, user_data):
user = get_user(update.effective_user, user_data)
cat_list = glob1("cats", "*.jp*g")
cat_pic = os.path.join('cats', random.choice(cat_list))
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=open(cat_pic, 'rb'))
def get_sample_count(path, classes):
count = 0
for name in class_names:
count += len(glob.glob1(path + name + '/', '*.png'))
return count
def _list_cache_files(self):
"""
Get a list of paths to all the cache files. These are all the files
in the root cache dir that end on the cache_suffix.
"""
if not os.path.exists(self._dir):
return []
filelist = [os.path.join(self._dir, fname) for fname
in glob.glob1(self._dir, '*%s' % self.cache_suffix)]
return filelist
def _list_cache_files(self):
"""
Get a list of paths to all the cache files. These are all the files
in the root cache dir that end on the cache_suffix.
"""
if not os.path.exists(self._dir):
return []
filelist = [os.path.join(self._dir, fname) for fname
in glob.glob1(self._dir, '*%s' % self.cache_suffix)]
return filelist
def _list_cache_files(self):
"""
Get a list of paths to all the cache files. These are all the files
in the root cache dir that end on the cache_suffix.
"""
if not os.path.exists(self._dir):
return []
filelist = [os.path.join(self._dir, fname) for fname
in glob.glob1(self._dir, '*%s' % self.cache_suffix)]
return filelist
def _list_cache_files(self):
"""
Get a list of paths to all the cache files. These are all the files
in the root cache dir that end on the cache_suffix.
"""
if not os.path.exists(self._dir):
return []
filelist = [os.path.join(self._dir, fname) for fname
in glob.glob1(self._dir, '*%s' % self.cache_suffix)]
return filelist
def demo():
import glob
winDir=win32api.GetWindowsDirectory()
for fileName in glob.glob1(winDir, '*.bmp')[:2]:
bitmapTemplate.OpenDocumentFile(os.path.join(winDir, fileName))
def loadTif(self):
self.path = QtGui.QFileDialog.getExistingDirectory(self, "Select Directory")
if self.path:
self.tifCounter = len(_glob.glob1(self.path, "*.tif"))
self.tifFiles = _glob.glob(os.path.join(self.path, "*.tif"))
self.table.setRowCount(int(self.tifCounter))
self.table.setColumnCount(6)
self.table.setHorizontalHeaderLabels(('FileName,Imager concentration[nM],Integration time [ms],Laserpower,Mean [Photons],Std [Photons]').split(','))
for i in range(0, self.tifCounter):
self.table.setItem(i, 0, QtGui.QTableWidgetItem(self.tifFiles[i]))
def content():
"""Return one dictionary that contains all dictionaries of the
module. By making a function rather than part of the namespace,
the content can be updated dynamically. Should not make any
difference in speed for normal use."""
global _contentCache
if _contentCache is not None:
return _contentCache
# import each time by looking at the files
mods = glob.glob1(__path__[0], '*.py')
_contentCache = content = {}
for m in mods:
if m[:2] == '__':
continue
modname = __name__ + '.' + m[:-3]
path = string.split(modname, '.')
module = __import__(modname)
# find the deepest submodule
for modname in path[1:]:
module = getattr(module, modname)
if hasattr(module, 'content'):
content.update(module.content)
continue
else:
if DEBUG:
print __name__, 'submodule ', module, 'misses a content dictionary.'
return content
def _list_cache_files(self):
"""
Get a list of paths to all the cache files. These are all the files
in the root cache dir that end on the cache_suffix.
"""
if not os.path.exists(self._dir):
return []
filelist = [os.path.join(self._dir, fname) for fname
in glob.glob1(self._dir, '*%s' % self.cache_suffix)]
return filelist
def demo():
import glob
winDir=win32api.GetWindowsDirectory()
for fileName in glob.glob1(winDir, '*.bmp')[:2]:
bitmapTemplate.OpenDocumentFile(os.path.join(winDir, fileName))
def get_last_checkpoint(model_dir):
list_of_models = glob.glob1(model_dir, '*.hdf5')
ckpt_epochs = [int(x.split('-')[-2]) for x in list_of_models]
print ckpt_epochs
latest_model_name = list_of_models[np.argsort(ckpt_epochs)[-1]]
epoch_num = int(latest_model_name.split('-')[-2])
print 'last snapshot:', latest_model_name
print 'last epoch=', epoch_num
return os.path.join(model_dir, latest_model_name), epoch_num
def _list_cache_files(self):
"""
Get a list of paths to all the cache files. These are all the files
in the root cache dir that end on the cache_suffix.
"""
if not os.path.exists(self._dir):
return []
filelist = [os.path.join(self._dir, fname) for fname
in glob.glob1(self._dir, '*%s' % self.cache_suffix)]
return filelist
def _list_cache_files(self):
"""
Get a list of paths to all the cache files. These are all the files
in the root cache dir that end on the cache_suffix.
"""
if not os.path.exists(self._dir):
return []
filelist = [os.path.join(self._dir, fname) for fname
in glob.glob1(self._dir, '*%s' % self.cache_suffix)]
return filelist
def _list_cache_files(self):
"""
Get a list of paths to all the cache files. These are all the files
in the root cache dir that end on the cache_suffix.
"""
if not os.path.exists(self._dir):
return []
filelist = [os.path.join(self._dir, fname) for fname
in glob.glob1(self._dir, '*%s' % self.cache_suffix)]
return filelist
def _list_cache_files(self):
"""
Get a list of paths to all the cache files. These are all the files
in the root cache dir that end on the cache_suffix.
"""
if not os.path.exists(self._dir):
return []
filelist = [os.path.join(self._dir, fname) for fname
in glob.glob1(self._dir, '*%s' % self.cache_suffix)]
return filelist
def find_modules(self, src_dir):
''' ?????? '''
for fn in glob.glob1(src_dir, '[!_]*.py'):
yield os.path.splitext(fn)[0]
def _list_cache_files(self):
"""
Get a list of paths to all the cache files. These are all the files
in the root cache dir that end on the cache_suffix.
"""
if not os.path.exists(self._dir):
return []
filelist = [os.path.join(self._dir, fname) for fname
in glob.glob1(self._dir, '*%s' % self.cache_suffix)]
return filelist
def _list_cache_files(self):
"""
Get a list of paths to all the cache files. These are all the files
in the root cache dir that end on the cache_suffix.
"""
if not os.path.exists(self._dir):
return []
filelist = [os.path.join(self._dir, fname) for fname
in glob.glob1(self._dir, '*%s' % self.cache_suffix)]
return filelist
def _list_cache_files(self):
"""
Get a list of paths to all the cache files. These are all the files
in the root cache dir that end on the cache_suffix.
"""
if not os.path.exists(self._dir):
return []
filelist = [os.path.join(self._dir, fname) for fname
in glob.glob1(self._dir, '*%s' % self.cache_suffix)]
return filelist
def theme_menu(self):
actions = self.menuTheme.actions()
for i in actions[2:]:
self.menuTheme.removeAction(i)
path = os.path.join(os.path.dirname(__file__), 'colors').replace('\\','/')
files = glob.glob1(path, '*.json')
for f in files:
full = os.path.join(path, f).replace('\\','/')
d = json.load(open(full))
a = QAction(d['name'], self, triggered=lambda f=d['name']:self.set_theme(f))
self.menuTheme.addAction(a)
def update_backup_menu(self):
actions = self.backup_menu_act.actions()
for i in actions[3:]:
self.backup_menu_act.removeAction(i)
backupdir = vex_settings.backup_folder()
for b in glob.glob1(backupdir, '*.backup'):
act = QAction(b, self)
# act.setData(os.path.join(backupdir, b).replace('\\','/'))
path = os.path.join(backupdir, b).replace('\\','/')
act.triggered.connect(lambda x=path: self.restore_backup(x))
self.backup_menu_act.addAction(act)
def get_themes(self):
path = self.themes_path()
themes = []
for c in glob.glob1(path, '*.json'):
try:
data = json.load(open(os.path.join(path, c)))
except:
continue
data['path'] = os.path.join(path, c).replace('\\','/')
themes.append(data)
return themes
def _list_cache_files(self):
"""
Get a list of paths to all the cache files. These are all the files
in the root cache dir that end on the cache_suffix.
"""
if not os.path.exists(self._dir):
return []
filelist = [os.path.join(self._dir, fname) for fname
in glob.glob1(self._dir, '*%s' % self.cache_suffix)]
return filelist
def _list_cache_files(self):
"""
Get a list of paths to all the cache files. These are all the files
in the root cache dir that end on the cache_suffix.
"""
if not os.path.exists(self._dir):
return []
filelist = [os.path.join(self._dir, fname) for fname
in glob.glob1(self._dir, '*%s' % self.cache_suffix)]
return filelist
def _list_cache_files(self):
"""
Get a list of paths to all the cache files. These are all the files
in the root cache dir that end on the cache_suffix.
"""
if not os.path.exists(self._dir):
return []
filelist = [os.path.join(self._dir, fname) for fname
in glob.glob1(self._dir, '*%s' % self.cache_suffix)]
return filelist
def _list_cache_files(self):
"""
Get a list of paths to all the cache files. These are all the files
in the root cache dir that end on the cache_suffix.
"""
if not os.path.exists(self._dir):
return []
filelist = [os.path.join(self._dir, fname) for fname
in glob.glob1(self._dir, '*%s' % self.cache_suffix)]
return filelist
def _list_cache_files(self):
"""
Get a list of paths to all the cache files. These are all the files
in the root cache dir that end on the cache_suffix.
"""
if not os.path.exists(self._dir):
return []
filelist = [os.path.join(self._dir, fname) for fname
in glob.glob1(self._dir, '*%s' % self.cache_suffix)]
return filelist
def _list_cache_files(self):
"""
Get a list of paths to all the cache files. These are all the files
in the root cache dir that end on the cache_suffix.
"""
if not os.path.exists(self._dir):
return []
filelist = [os.path.join(self._dir, fname) for fname
in glob.glob1(self._dir, '*%s' % self.cache_suffix)]
return filelist