本文整理汇总了Python中os.fspath方法的典型用法代码示例。如果您正苦于以下问题:Python os.fspath方法的具体用法?Python os.fspath怎么用?Python os.fspath使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类os
的用法示例。
在下文中一共展示了os.fspath方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import os [as 别名]
# 或者: from os import fspath [as 别名]
def __init__(self, path, mode=DEFAULT_MODE, overwrite=False,
**open_kwargs):
if 'a' in mode:
raise ValueError(
'Appending to an existing file is not supported, because that '
'would involve an expensive `copy`-operation to a temporary '
'file. Open the file in normal `w`-mode and copy explicitly '
'if that\'s what you\'re after.'
)
if 'x' in mode:
raise ValueError('Use the `overwrite`-parameter instead.')
if 'w' not in mode:
raise ValueError('AtomicWriters can only be written to.')
# Attempt to convert `path` to `str` or `bytes`
if fspath is not None:
path = fspath(path)
self._path = path
self._mode = mode
self._overwrite = overwrite
self._open_kwargs = open_kwargs
示例2: split
# 需要导入模块: import os [as 别名]
# 或者: from os import fspath [as 别名]
def split(p):
"""Split a pathname. Returns tuple "(head, tail)" where "tail" is
everything after the final slash. Either part may be empty."""
p = os.fspath(p)
sep = _get_sep(p)
i = p.rfind(sep) + 1
head, tail = p[:i], p[i:]
if head and head != sep*len(head):
head = head.rstrip(sep)
return head, tail
# Split a path in root and extension.
# The extension is everything starting at the last dot in the last
# pathname component; the root is everything before that.
# It is always true that root + ext == p.
示例3: presigned_url
# 需要导入模块: import os [as 别名]
# 或者: from os import fspath [as 别名]
def presigned_url(self, url, expiration=60, force_download=False):
"""Create a presigned URL.
The URL is used to obtain temporary access to the object ar the
given URL using only returned URL.
:param expiration: expiration time of the link (in seconds), default
is one minute.
:param force_download: force download.
:returns: URL that can be used to access object or None.
"""
content_disposition = "attachment" if force_download else "inline"
query_parameters = {"response-content-disposition": content_disposition}
blob = self.bucket.blob(os.fspath(url))
response = blob.generate_signed_url(
version="v4",
expiration=datetime.timedelta(seconds=expiration),
method="GET",
virtual_hosted_style=True,
query_parameters=query_parameters,
)
return response
示例4: get_hashes
# 需要导入模块: import os [as 别名]
# 或者: from os import fspath [as 别名]
def get_hashes(self, url, hash_types):
"""Get the hash of the given type for the given object."""
resource = self.awss3.Object(self.bucket_name, os.fspath(url))
hashes = dict()
try:
for hash_type in hash_types:
if hash_type in self.hash_propery:
prop = self.hash_propery[hash_type]
hashes[hash_type] = getattr(resource, prop).strip('"')
else:
hashes[hash_type] = resource.metadata.get(hash_type)
except botocore.exceptions.ClientError as error:
if error.response["Error"]["Code"] == "404":
return None
else:
# Something else has gone wrong.
raise
return hashes
示例5: set_hashes
# 需要导入模块: import os [as 别名]
# 或者: from os import fspath [as 别名]
def set_hashes(self, url, hashes):
"""Set the hashes for the given object."""
# Changing metadata on existing objects in S3 is annoyingly hard.
# See
# https://boto3.amazonaws.com/v1/documentation/api/1.9.42/guide/s3.html
# under managed copy for example.
# If one uses copy_object method proposed by some solutions the e_tag
# value on object can (and will) change. That causes error downloading
# since hash check fails.
url = os.fspath(url)
head = self.client.head_object(Bucket=self.bucket_name, Key=url)
meta = head["Metadata"]
hashes = {k: v for (k, v) in hashes.items() if k not in self.hash_propery}
meta.update(hashes)
copy_source = {
"Bucket": self.bucket_name,
"Key": url,
}
self.client.copy(
copy_source,
self.bucket_name,
url,
ExtraArgs={"Metadata": meta, "MetadataDirective": "REPLACE"},
)
示例6: read
# 需要导入模块: import os [as 别名]
# 或者: from os import fspath [as 别名]
def read(self, filenames, encoding=None):
"""Read and parse a filename or an iterable of filenames.
Files that cannot be opened are silently ignored; this is
designed so that you can specify an iterable of potential
configuration file locations (e.g. current directory, user's
home directory, systemwide directory), and all existing
configuration files in the iterable will be read. A single
filename may also be given.
Return list of successfully read files.
"""
if isinstance(filenames, (str, bytes, os.PathLike)):
filenames = [filenames]
read_ok = []
for filename in filenames:
try:
with open(filename, encoding=encoding) as fp:
self._read(fp, filename)
except OSError:
continue
if isinstance(filename, os.PathLike):
filename = os.fspath(filename)
read_ok.append(filename)
return read_ok
示例7: from_toml
# 需要导入模块: import os [as 别名]
# 或者: from os import fspath [as 别名]
def from_toml(cls: Type["Config"], filename: FilePath) -> "Config":
"""Load the configuration values from a TOML formatted file.
This allows configuration to be loaded as so
.. code-block:: python
Config.from_toml('config.toml')
Arguments:
filename: The filename which gives the path to the file.
"""
file_path = os.fspath(filename)
with open(file_path) as file_:
data = toml.load(file_)
return cls.from_mapping(data)
示例8: normcase
# 需要导入模块: import os [as 别名]
# 或者: from os import fspath [as 别名]
def normcase(s):
"""Normalize case of pathname.
Makes all characters lowercase and all slashes into backslashes."""
s = os.fspath(s)
try:
if isinstance(s, bytes):
return s.replace(b'/', b'\\').lower()
else:
return s.replace('/', '\\').lower()
except (TypeError, AttributeError):
if not isinstance(s, (bytes, str)):
raise TypeError("normcase() argument must be str or bytes, "
"not %r" % s.__class__.__name__) from None
raise
# Return whether a path is absolute.
# Trivial in Posix, harder on Windows.
# For Windows it is absolute if it starts with a slash or backslash (current
# volume), or if a pathname after the volume-letter-and-colon or UNC-resource
# starts with a slash or backslash.
示例9: commonprefix
# 需要导入模块: import os [as 别名]
# 或者: from os import fspath [as 别名]
def commonprefix(m):
"Given a list of pathnames, returns the longest common leading component"
if not m: return ''
# Some people pass in a list of pathname parts to operate in an OS-agnostic
# fashion; don't try to translate in that case as that's an abuse of the
# API and they are already doing what they need to be OS-agnostic and so
# they most likely won't be using an os.PathLike object in the sublists.
if not isinstance(m[0], (list, tuple)):
m = tuple(map(os.fspath, m))
s1 = min(m)
s2 = max(m)
for i, c in enumerate(s1):
if c != s2[i]:
return s1[:i]
return s1
# Are two stat buffers (obtained from stat, fstat or lstat)
# describing the same file?
示例10: fspath
# 需要导入模块: import os [as 别名]
# 或者: from os import fspath [as 别名]
def fspath(path):
"""
Return the string representation of the path.
If str or bytes is passed in, it is returned unchanged.
This code comes from PEP 519, modified to support earlier versions of
python.
This is required for python < 3.6.
"""
if isinstance(path, (py.builtin.text, py.builtin.bytes)):
return path
# Work from the object's type to match method resolution of other magic
# methods.
path_type = type(path)
try:
return path_type.__fspath__(path)
except AttributeError:
if hasattr(path_type, '__fspath__'):
raise
try:
import pathlib
except import_errors:
pass
else:
if isinstance(path, pathlib.PurePath):
return py.builtin.text(path)
raise TypeError("expected str, bytes or os.PathLike object, not "
+ path_type.__name__)
示例11: jinja_loader
# 需要导入模块: import os [as 别名]
# 或者: from os import fspath [as 别名]
def jinja_loader(self) -> Optional[FileSystemLoader]:
if self.template_folder is not None:
return FileSystemLoader(os.fspath(self.root_path / self.template_folder))
else:
return None
示例12: __div__
# 需要导入模块: import os [as 别名]
# 或者: from os import fspath [as 别名]
def __div__(self, other):
return self.join(fspath(other))
示例13: test_fspath_func_match_strpath
# 需要导入模块: import os [as 别名]
# 或者: from os import fspath [as 别名]
def test_fspath_func_match_strpath(self, path1):
try:
from os import fspath
except ImportError:
from py._path.common import fspath
assert fspath(path1) == path1.strpath
示例14: test_excelfile_fspath
# 需要导入模块: import os [as 别名]
# 或者: from os import fspath [as 别名]
def test_excelfile_fspath(self):
with tm.ensure_clean('foo.xlsx') as path:
df = DataFrame({"A": [1, 2]})
df.to_excel(path)
xl = ExcelFile(path)
result = os.fspath(xl)
assert result == path
示例15: test_excelwriter_fspath
# 需要导入模块: import os [as 别名]
# 或者: from os import fspath [as 别名]
def test_excelwriter_fspath(self):
with tm.ensure_clean('foo.xlsx') as path:
writer = ExcelWriter(path)
assert os.fspath(writer) == str(path)