本文整理匯總了Python中clldutils.path.Path.exists方法的典型用法代碼示例。如果您正苦於以下問題:Python Path.exists方法的具體用法?Python Path.exists怎麽用?Python Path.exists使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類clldutils.path.Path
的用法示例。
在下文中一共展示了Path.exists方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __init__
# 需要導入模塊: from clldutils.path import Path [as 別名]
# 或者: from clldutils.path.Path import exists [as 別名]
def __init__(self, name, default=None, **kw):
"""Initialization.
:param name: Basename for the config file (suffix .ini will be appended).
:param default: Default content of the config file.
"""
self.name = name
self.default = default
config_dir = Path(kw.pop('config_dir', None) or DIR)
RawConfigParser.__init__(self, kw, allow_no_value=True)
if self.default:
if PY3:
fp = io.StringIO(self.default)
else:
fp = io.BytesIO(self.default.encode('utf8'))
self.readfp(fp)
cfg_path = config_dir.joinpath(name + '.ini')
if cfg_path.exists():
assert cfg_path.is_file()
self.read(cfg_path.as_posix())
else:
if not config_dir.exists():
try:
config_dir.mkdir()
except OSError: # pragma: no cover
# this happens when run on travis-ci, by a system user.
pass
if config_dir.exists():
with open(cfg_path.as_posix(), 'w') as fp:
self.write(fp)
self.path = cfg_path
示例2: link
# 需要導入模塊: from clldutils.path import Path [as 別名]
# 或者: from clldutils.path.Path import exists [as 別名]
def link(args):
"""\
Complete linking of concepts to concept sets. If either CONCEPTICON_GLOSS or
CONCEPTICON_ID is given, the other is added.
concepticon link <concept-list>
"""
conceptlist = Path(args.args[0])
if not conceptlist.exists() or not conceptlist.is_file():
conceptlist = data_path('conceptlists', args.args[0])
if not conceptlist.exists() or not conceptlist.is_file():
raise ParserError('no file %s found' % args.args[0])
rewrite(conceptlist, Linker(conceptlist.stem))
示例3: wals_detail_html
# 需要導入模塊: from clldutils.path import Path [as 別名]
# 或者: from clldutils.path.Path import exists [as 別名]
def wals_detail_html(context=None, request=None, **kw):
wals_data = Path(apics.__file__).parent.joinpath(
'static', 'wals', '%sA.json' % context.parameter.wals_id)
if not wals_data.exists():
raise HTTPNotFound()
wals_data = jsonlib.load(wals_data)
value_map = {}
for layer in wals_data['layers']:
for feature in layer['features']:
feature['properties']['icon'] = request.registry.getUtility(
IIcon, name=feature['properties']['icon']).url(request)
feature['properties']['popup'] = external_link(
'http://wals.info/languoid/lect/wals_code_'
+ feature['properties']['language']['id'],
label=feature['properties']['language']['name'])
value_map[layer['properties']['number']] = {
'icon': layer['features'][0]['properties']['icon'],
'name': layer['properties']['name'],
'number': layer['properties']['number'],
}
return {
'wals_data': wals_data,
'wals_map': WalsMap(
context.parameter, request, data=wals_data, value_map=value_map),
'apics_map': ApicsWalsMap(
context.parameter, request, data=wals_data, value_map=value_map)}
示例4: write
# 需要導入模塊: from clldutils.path import Path [as 別名]
# 或者: from clldutils.path.Path import exists [as 別名]
def write(self, outdir='.', suffix='.csv', cited_sources_only=False, archive=False):
outdir = Path(outdir)
if not outdir.exists():
raise ValueError(outdir.as_posix())
close = False
if archive:
if isinstance(archive, Archive):
container = archive
else:
container = Archive(outdir.joinpath(self.name + '.zip'), mode='w')
close = True
else:
container = outdir
fname = Path(outdir).joinpath(self.name + suffix)
if fname.suffix in TAB_SUFFIXES:
self.table.dialect.delimiter = '\t'
with UnicodeWriter(
None if isinstance(container, Archive) else fname,
delimiter=self.table.dialect.delimiter) as writer:
writer.writerow(self.fields)
for row in self.rows:
writer.writerow(row.to_list())
if isinstance(container, Archive):
container.write_text(writer.read(), fname.name)
self.table.url = fname.name
self.metadata.write(Dataset.filename(fname, 'metadata'), container)
ids = self._cited_sources if cited_sources_only else None
self.sources.write(Dataset.filename(fname, 'sources'), container, ids=ids)
if close:
container.close()
示例5: __call__
# 需要導入模塊: from clldutils.path import Path [as 別名]
# 或者: from clldutils.path.Path import exists [as 別名]
def __call__(self, parser, namespace, values, option_string=None):
path_ = Path(values)
if not path_.exists():
raise argparse.ArgumentError(self, "path does not exist")
if not path_.is_dir():
raise argparse.ArgumentError(self, "path is no directory")
setattr(namespace, self.dest, path_)
示例6: stats
# 需要導入模塊: from clldutils.path import Path [as 別名]
# 或者: from clldutils.path.Path import exists [as 別名]
def stats(args):
"""
cldf stats <DATASET>
Print basic stats for CLDF dataset <DATASET>, where <DATASET> may be the path to
- a CLDF metadata file
- a CLDF core data file
- a CLDF zip archive
"""
if len(args.args) < 1:
raise ParserError('not enough arguments')
fname = Path(args.args[0])
if not fname.exists() or not fname.is_file():
raise ParserError('%s is not an existing directory' % fname)
if fname.suffix == '.zip':
ds = Dataset.from_zip(fname)
elif fname.name.endswith(MD_SUFFIX):
ds = Dataset.from_metadata(fname)
else:
ds = Dataset.from_file(fname)
print(fname)
stats_ = ds.stats
print("""
Name: %s
Different languages: %s
Different parameters: %s
Rows: %s
""" % (
ds.name,
len(stats_['languages']),
len(stats_['parameters']),
stats_['rowcount']
))
示例7: to_cldf
# 需要導入模塊: from clldutils.path import Path [as 別名]
# 或者: from clldutils.path.Path import exists [as 別名]
def to_cldf(self, dest, mdname='cldf-metadata.json'):
"""
Write the data from the db to a CLDF dataset according to the metadata in `self.dataset`.
:param dest:
:param mdname:
:return: path of the metadata file
"""
dest = Path(dest)
if not dest.exists():
dest.mkdir()
data = self.read()
if data[self.source_table_name]:
sources = Sources()
for src in data[self.source_table_name]:
sources.add(Source(
src['genre'],
src['id'],
**{k: v for k, v in src.items() if k not in ['id', 'genre']}))
sources.write(dest / self.dataset.properties.get('dc:source', 'sources.bib'))
for table_type, items in data.items():
try:
table = self.dataset[table_type]
table.common_props['dc:extent'] = table.write(
[self.retranslate(table, item) for item in items],
base=dest)
except KeyError:
assert table_type == self.source_table_name, table_type
return self.dataset.write_metadata(dest / 'cldf-metadata.json')
示例8: lff2tree
# 需要導入模塊: from clldutils.path import Path [as 別名]
# 或者: from clldutils.path.Path import exists [as 別名]
def lff2tree(tree=TREE, outdir=None, builddir=None, lffs=None):
"""
- get mapping glottocode -> Languoid from old tree
- assemble new directory tree
- for each path component in lff/dff:
- create new dir
- copy info file from old tree (possibly updating the name) or
- create info file
- for each language/dialect in lff/dff:
- create new dir
- copy info file from old tree (possibly updating the name) or
- create info file
- rm old tree
- copy new tree
"""
# FIXME: instead of removing trees, we should just move the current one
# from outdir to build, and then recreate in outdir.
builddir = Path(builddir) if builddir else build_path("tree")
old_tree = {l.id: l for l in walk_tree(tree)} if tree else {}
out = Path(outdir or tree)
if not out.parent.exists():
out.parent.mkdir()
if out.exists():
if builddir.exists():
try:
rmtree(builddir)
except: # pragma: no cover
pass
if builddir.exists(): # pragma: no cover
raise ValueError("please remove %s before proceeding" % builddir)
# move the old tree out of the way
shutil.move(out.as_posix(), builddir.as_posix())
out.mkdir()
lffs = lffs or {}
languages = {}
for lang in read_lff(Level.language, fp=lffs.get(Level.language)):
languages[lang.id] = lang
lang2tree(lang, lang.lineage, out, old_tree)
for lang in read_lff(Level.dialect, fp=lffs.get(Level.dialect)):
if not lang.lineage or lang.lineage[0][1] not in languages:
raise ValueError("unattached dialect") # pragma: no cover
lang2tree(lang, languages[lang.lineage[0][1]].lineage + lang.lineage, out, old_tree)
示例9: _get_dataset
# 需要導入模塊: from clldutils.path import Path [as 別名]
# 或者: from clldutils.path.Path import exists [as 別名]
def _get_dataset(args):
if len(args.args) < 1:
raise ParserError('not enough arguments')
fname = Path(args.args[0])
if not fname.exists() or not fname.is_file():
raise ParserError('%s is not an existing directory' % fname)
if fname.suffix == '.json':
return Dataset.from_metadata(fname)
return Dataset.from_data(fname)
示例10: in_dir
# 需要導入模塊: from clldutils.path import Path [as 別名]
# 或者: from clldutils.path.Path import exists [as 別名]
def in_dir(cls, d, empty_tables=False):
fname = Path(d)
if not fname.exists():
fname.mkdir()
assert fname.is_dir()
res = cls.from_metadata(fname)
if empty_tables:
del res.tables[:]
return res
示例11: write_data_file
# 需要導入模塊: from clldutils.path import Path [as 別名]
# 或者: from clldutils.path.Path import exists [as 別名]
def write_data_file(comment_text, overwrite):
lines = comment_text.split("\n")
filename = Path(lines[0].split(":",1)[1].strip())
if filename.exists() and not overwrite:
return "Embedded data file %s already exists! Run beastling with the --overwrite option if you wish to overwrite it.\n" % filename
if not filename.parent.exists():
filename.parent.mkdir()
with filename.open("w", encoding='utf8') as fp:
fp.write("\n".join(lines[1:]))
return "Wrote embedded data file %s.\n" % filename
示例12: TemporaryPath
# 需要導入模塊: from clldutils.path import Path [as 別名]
# 或者: from clldutils.path.Path import exists [as 別名]
class TemporaryPath(object):
def __init__(self, suffix=''):
fp = NamedTemporaryFile(suffix=suffix)
self.name = Path(fp.name)
fp.close()
def __enter__(self):
return self.name.as_posix()
def __exit__(self, exc_type, exc_val, exc_tb):
if self.name.exists():
remove(self.name)
示例13: safe_overwrite
# 需要導入模塊: from clldutils.path import Path [as 別名]
# 或者: from clldutils.path.Path import exists [as 別名]
def safe_overwrite(fname):
fname = Path(fname)
if not fname.parent.exists():
fname.parent.mkdir()
assert fname.parent.exists()
tmp = fname.parent
while tmp.exists():
tmp = fname.parent.joinpath('%s.%s' % (fname.name, random_string(6)))
yield tmp
if fname.exists():
remove(fname)
move(tmp, fname)
示例14: test_generate_extract
# 需要導入模塊: from clldutils.path import Path [as 別名]
# 或者: from clldutils.path.Path import exists [as 別名]
def test_generate_extract(self):
xml = self.tmp_path('test.xml')
self._run_main('-v -o {0} {1}'.format(xml.as_posix(), config_path('basic')))
self.assertTrue(xml.exists())
# Overwriting existing files must be specified explicitely:
self._run_main('-o {0} {1}'.format(
xml.as_posix(), config_path('basic')), status=4)
self._run_main('--overwrite -o {0} {1}'.format(
xml.as_posix(), config_path('basic')), status=0)
tcfg = Path('beastling_test.conf')
self._run_main('--extract {0}'.format(xml.as_posix()))
self.assertTrue(tcfg.exists())
remove(tcfg)
示例15: write_info
# 需要導入模塊: from clldutils.path import Path [as 別名]
# 或者: from clldutils.path.Path import exists [as 別名]
def write_info(self, outdir=None):
outdir = outdir or self.id
if not isinstance(outdir, Path):
outdir = Path(outdir)
if not outdir.exists():
outdir.mkdir()
fname = outdir.joinpath(self.fname('.ini'))
self.cfg.write(fname)
if os.linesep == '\n':
with fname.open(encoding='utf8') as fp:
text = fp.read()
with fname.open('w', encoding='utf8') as fp:
fp.write(text.replace('\n', '\r\n'))
return fname