本文整理汇总了Python中pathlib.Path.exists方法的典型用法代码示例。如果您正苦于以下问题:Python Path.exists方法的具体用法?Python Path.exists怎么用?Python Path.exists使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pathlib.Path
的用法示例。
在下文中一共展示了Path.exists方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_logging_failing_explore_sql
# 需要导入模块: from pathlib import Path [as 别名]
# 或者: from pathlib.Path import exists [as 别名]
def test_logging_failing_explore_sql(tmpdir, sql_error):
sql_error.metadata["dimension"] = None
expected_directory = Path(tmpdir) / "queries"
expected_directory.mkdir(exist_ok=True)
log_sql_error(
sql_error.model,
sql_error.explore,
sql_error.metadata["sql"],
tmpdir,
sql_error.metadata["dimension"],
)
expected_path = expected_directory / "eye_exam__users.sql"
assert Path.exists(expected_path)
with expected_path.open("r") as file:
content = file.read()
assert content == "SELECT age FROM users WHERE 1=2 LIMIT 1"
示例2: test_logging_failing_dimension_sql
# 需要导入模块: from pathlib import Path [as 别名]
# 或者: from pathlib.Path import exists [as 别名]
def test_logging_failing_dimension_sql(tmpdir, sql_error):
expected_directory = Path(tmpdir) / "queries"
expected_directory.mkdir(exist_ok=True)
log_sql_error(
sql_error.model,
sql_error.explore,
sql_error.metadata["sql"],
tmpdir,
sql_error.metadata["dimension"],
)
expected_path = expected_directory / "eye_exam__users__users_age.sql"
assert Path.exists(expected_path)
with expected_path.open("r") as file:
content = file.read()
assert content == "SELECT age FROM users WHERE 1=2 LIMIT 1"
示例3: get_mathlib_olean
# 需要导入模块: from pathlib import Path [as 别名]
# 或者: from pathlib.Path import exists [as 别名]
def get_mathlib_olean(self) -> None:
"""Get precompiled mathlib oleans for this project."""
# Just in case the user broke the workflow (for instance git clone
# mathlib by hand and then run `leanproject get-cache`)
if not (self.directory/'leanpkg.path').exists():
self.run(['leanpkg', 'configure'])
try:
archive = get_mathlib_archive(self.mathlib_rev, self.cache_url,
self.force_download, self.repo)
except (EOFError, shutil.ReadError):
log.info('Something wrong happened with the olean archive. '
'I will now retry downloading.')
archive = get_mathlib_archive(self.mathlib_rev, self.cache_url,
True, self.repo)
self.clean_mathlib()
self.mathlib_folder.mkdir(parents=True, exist_ok=True)
unpack_archive(archive, self.mathlib_folder)
# Let's now touch oleans, just in case
touch_oleans(self.mathlib_folder)
示例4: endFile
# 需要导入模块: from pathlib import Path [as 别名]
# 或者: from pathlib.Path import exists [as 别名]
def endFile(self):
if self.errFile:
self.errFile.flush()
if self.warnFile:
self.warnFile.flush()
if self.diagFile:
self.diagFile.flush()
self.outFile.flush()
if self.outFile != sys.stdout and self.outFile != sys.stderr:
self.outFile.close()
# On successfully generating output, move the temporary file to the
# target file.
if self.genOpts.filename is not None:
if sys.platform == 'win32':
directory = Path(self.genOpts.directory)
if not Path.exists(directory):
os.makedirs(directory)
shutil.move(self.outFile.name, self.genOpts.directory + '/' + self.genOpts.filename)
self.genOpts = None
示例5: initializeTestDefinition
# 需要导入模块: from pathlib import Path [as 别名]
# 或者: from pathlib.Path import exists [as 别名]
def initializeTestDefinition(self):
steps = []
try:
with open(self.csvFileName+".csv") as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
index =0
for col in row:
expression = Path(os.path.join(self.confFile.getElementsByTagName("jsonsRepoPath")[0].firstChild.data,row[col]))
#pathExpected = Path((str(Path(__file__).parents[3]) + str(expression)))
pathExpected = os.path.join(str(self.dirPath),str(expression).rstrip())
if row[col]!="":
if Path.exists(Path(pathExpected)) :
steps.append(Step(row[col],index))
index+=1
else:
raise Exception
return steps
except Exception as e:
raise IOError("the file " + self.csvFileName + " or the jsons file inside the csv rows not found")
开发者ID:Wireless-Innovation-Forum,项目名称:Citizens-Broadband-Radio-Service-Device,代码行数:22,代码来源:CsvFileParser.py
示例6: test_fsdir
# 需要导入模块: from pathlib import Path [as 别名]
# 或者: from pathlib.Path import exists [as 别名]
def test_fsdir(tmp_path, spaces):
fshome = os.environ["FREESURFER_HOME"]
subjects_dir = tmp_path / "freesurfer"
# Verify we're starting clean
for space in spaces:
if space.startswith("fsaverage"):
assert not Path.exists(subjects_dir / space)
# Run three times to check idempotence
# Third time force an overwrite
for overwrite_fsaverage in (False, False, True):
res = bintfs.BIDSFreeSurferDir(
derivatives=str(tmp_path),
spaces=spaces,
freesurfer_home=fshome,
overwrite_fsaverage=overwrite_fsaverage,
).run()
assert res.outputs.subjects_dir == str(subjects_dir)
for space in spaces:
if space.startswith("fsaverage"):
assert Path.exists(subjects_dir / space)
示例7: test_fsdir_missing_space
# 需要导入模块: from pathlib import Path [as 别名]
# 或者: from pathlib.Path import exists [as 别名]
def test_fsdir_missing_space(tmp_path):
fshome = os.environ["FREESURFER_HOME"]
# fsaverage2 doesn't exist in source or destination, so can't copy
with pytest.raises(FileNotFoundError):
bintfs.BIDSFreeSurferDir(
derivatives=str(tmp_path), spaces=["fsaverage2"], freesurfer_home=fshome
).run()
subjects_dir = tmp_path / "freesurfer"
# If fsaverage2 exists in the destination directory, no error is thrown
Path.mkdir(subjects_dir / "fsaverage2")
bintfs.BIDSFreeSurferDir(
derivatives=str(tmp_path), spaces=["fsaverage2"], freesurfer_home=fshome
).run()
示例8: test_inject_skullstrip
# 需要导入模块: from pathlib import Path [as 别名]
# 或者: from pathlib.Path import exists [as 别名]
def test_inject_skullstrip(tmp_path):
t1_mgz = tmp_path / "sub-01" / "mri" / "T1.mgz"
t1_mgz.parent.mkdir(parents=True)
# T1.mgz images are uint8
nb.MGHImage(np.ones((5, 5, 5), dtype=np.uint8), np.eye(4)).to_filename(str(t1_mgz))
mask_nii = tmp_path / "mask.nii.gz"
# Masks may be in a different space (and need resampling), but should be boolean,
# or uint8 in NIfTI
nb.Nifti1Image(np.ones((6, 6, 6), dtype=np.uint8), np.eye(4)).to_filename(
str(mask_nii)
)
FSInjectBrainExtracted(
subjects_dir=str(tmp_path), subject_id="sub-01", in_brain=str(mask_nii)
).run()
assert Path.exists(tmp_path / "sub-01" / "mri" / "brainmask.auto.mgz")
assert Path.exists(tmp_path / "sub-01" / "mri" / "brainmask.mgz")
# Run a second time to hit "already exists" condition
FSInjectBrainExtracted(
subjects_dir=str(tmp_path), subject_id="sub-01", in_brain=str(mask_nii)
).run()
示例9: load_row_table
# 需要导入模块: from pathlib import Path [as 别名]
# 或者: from pathlib.Path import exists [as 别名]
def load_row_table(self, session: Session):
"""
Load the row table with values from min to max.
:session:
:return:
"""
for row_ind in range(ROW_MIN, ROW_MAX + 1):
row_key = f'{row_ind:02}'
row_descr = f'Row {row_key}'
try:
session.add(self.LocRow(loc_row=row_key,
loc_row_descr=row_descr))
session.commit()
except IntegrityError:
print(f'Row {row_ind} already exists')
session.rollback()
for record in session.query(self.LocRow):
print(f'Row: {record.loc_row} {record.loc_row_descr} ')
return
示例10: load_bin_table
# 需要导入模块: from pathlib import Path [as 别名]
# 或者: from pathlib.Path import exists [as 别名]
def load_bin_table(self, session: Session):
"""
Load the bin table with values from min to max.
:return:
"""
for bin_ind in range(BIN_MIN, BIN_MAX + 1):
bin_key = f'{bin_ind:02}'
bin_descr = f'Bin {bin_key}'
try:
session.add(self.LocBin(loc_bin=bin_key,
loc_bin_descr=bin_descr))
session.commit()
except IntegrityError:
print(f'Bin {bin_ind} already exists')
session.rollback()
for record in session.query(self.LocBin):
print(f'Bin: {record.loc_bin} {record.loc_bin_descr} ')
示例11: load_tier_table
# 需要导入模块: from pathlib import Path [as 别名]
# 或者: from pathlib.Path import exists [as 别名]
def load_tier_table(self, session: Session):
"""
Load the tier table with values from the list.
:return:
"""
for tier_ind in TIER_LIST:
tier_key = f'{tier_ind}'
tier_descr = f'Tier {tier_key}'
try:
session.add(self.LocTier(loc_tier=tier_key,
loc_tier_descr=tier_descr))
session.commit()
except IntegrityError:
print(f'Tier {tier_ind} already exists')
session.rollback()
for record in session.query(self.LocTier):
print(f'Tier: {record.loc_tier} {record.loc_tier_descr} ')
示例12: validate_parameter_value
# 需要导入模块: from pathlib import Path [as 别名]
# 或者: from pathlib.Path import exists [as 别名]
def validate_parameter_value(input_name, input_value, min_value=None, max_value=None, possible_values=None):
if isinstance(input_value, PurePath):
if not Path.exists(input_value): # pragma: no cover
raise ValueError("Given path: " + str(input_value) + " does not exist.")
if input_value is not None:
if min_value is not None:
if input_value < min_value: # pragma: no cover
raise ValueError(
"Invalid value for " + str(input_name) + " supplied: " + str(input_value) + ". Provide a value greater than or equal to " + str(min_value) + ".")
if input_value is not None:
if max_value is not None:
if input_value > max_value: # pragma: no cover
raise ValueError(
"Invalid value for " + str(input_name) + " supplied: " + str(input_value) + ". Provide a value less than or equal to " + str(max_value) + ".")
if possible_values is not None:
if input_value not in possible_values: # pragma: no cover
raise ValueError(
"Invalid value for " + str(input_name) + " supplied: " + str(input_value) + ". Provide a value from: " + str(possible_values) + ".")
return True
示例13: create_dir
# 需要导入模块: from pathlib import Path [as 别名]
# 或者: from pathlib.Path import exists [as 别名]
def create_dir(name):
if not Path.exists(name):
Path.mkdir(name)
示例14: get_mathlib_archive
# 需要导入模块: from pathlib import Path [as 别名]
# 或者: from pathlib.Path import exists [as 别名]
def get_mathlib_archive(rev: str, url:str = '', force: bool = False,
repo: Optional[Repo] = None) -> Path:
"""Download a mathlib archive for revision rev into .mathlib
Return the archive Path. Will raise LeanDownloadError if nothing works.
"""
# we check for xz archives first
fnames = [rev + '.tar.xz', rev + '.tar.gz', rev + '.tar.bz2']
paths = [DOT_MATHLIB/fname for fname in fnames]
if not force:
log.info('Looking for local mathlib oleans')
for path in paths:
if path.exists():
log.info('Found local mathlib oleans')
return path
log.info('Looking for remote mathlib oleans')
for fname, path in zip(fnames, paths):
try:
base_url = url or get_download_url()
download(base_url+fname, path)
log.info('Found mathlib oleans at '+base_url)
return path
except LeanDownloadError:
pass
log.info('Looking for GitHub mathlib oleans')
# nightlies will only store gz archives
path = DOT_MATHLIB / (rev + '.tar.gz')
download(nightly_url(rev, repo), path)
log.info('Found GitHub mathlib oleans')
return path
示例15: delete_zombies
# 需要导入模块: from pathlib import Path [as 别名]
# 或者: from pathlib.Path import exists [as 别名]
def delete_zombies(dir: Path) -> None:
for path in dir.glob('**/*.olean'):
if not path.with_suffix('.lean').exists():
log.info('deleting zombie {} ...'.format(str(path)))
path.unlink()