本文整理汇总了Python中clldutils.path.Path类的典型用法代码示例。如果您正苦于以下问题:Python Path类的具体用法?Python Path怎么用?Python Path使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Path类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: stats
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']
))
示例2: to_cldf
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')
示例3: write
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()
示例4: wals_detail_html
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)}
示例5: __call__
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: in_dir
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
示例7: _get_dataset
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)
示例8: copy_downloads
def copy_downloads(app, pattern='*'):
dl_dir = app.src.joinpath(app.name, 'static', 'download')
require.files.directory(dl_dir, use_sudo=True, mode="777")
local_dl_dir = Path(import_module(app.name).__file__).parent.joinpath('static', 'download')
for f in local_dl_dir.glob(pattern):
target = dl_dir.joinpath(f.name)
create_file_as_root(target, open(f.as_posix()).read())
sudo('chown %s:%s %s' % (app.name, app.name, target))
require.files.directory(dl_dir, use_sudo=True, mode="755")
示例9: write_data_file
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
示例10: safe_overwrite
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)
示例11: TemporaryPath
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)
示例12: load_normalized
def load_normalized(_path):
"""Normalization for quasi-identical strings which are often confused."""
path = Path(_path)
if not path.is_file():
path = local_path(_path)
norms = {}
with path.open(encoding='utf-8') as handle:
for line in handle:
if not line.startswith('#') and line.strip():
source, target = line.strip().split('\t')
norms[eval('"' + source + '"')] = eval('r"' + target + '"')
return norms
示例13: test_generate_extract
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)
示例14: create
def create(self, dir_, content):
"""Write ``content`` to a file using ``dir_`` as file-system directory.
:return: File-system path of the file that was created.
"""
if not isinstance(dir_, Path):
dir_ = Path(dir_)
p = dir_.joinpath(self.relpath)
if not p.parent.exists():
p.parent.mkdir(parents=True)
with open(p.as_posix(), 'wb') as fp:
fp.write(content)
return p.as_posix()
示例15: dependencies_graph
def dependencies_graph(imps):
deps = dict([((f1, f2), v) for (v, f1, f2) in imps if v > 0.0])
V = set([f for fs in deps.iterkeys() for f in fs])
G = dict([(k, v) for (k, v) in deps.items() if v > 0.0])
MSTs = [mst(G, x) for x in V]
(mv, H) = max([(sum(H.values()), H) for H in MSTs])
#W = dict([(y, 1.0-v) for ((x, y), v) in H.iteritems()])
#sav(dot(H, V), 'grambank_mst.gv')
path = Path(grambank.__file__).parent.joinpath('static', 'dependencies.gv')
with open(path.as_posix(), 'w') as fp:
fp.write(dot(H, V))
return (H, V) #dot(H, V)