fs.wrap¶
Collection of useful WrapFS subclasses.
Here’s an example that opens a filesystem then makes it read only:
>>> home_fs = fs.open_fs('~')
>>> read_only_home_fs = fs.wrap.read_only(home_fs)
>>> read_only_home_fs.removedir('Desktop')
Traceback (most recent call last):
...
fs.errors.ResourceReadOnly: resource 'Desktop' is read only
- class fs.wrap.WrapCachedDir(wrap_fs: _F)[source]¶
Caches filesystem directory information.
This filesystem caches directory information retrieved from a scandir call. This may speed up code that calls
isdir,isfile, orgettypetoo frequently.Note
Using this wrap will prevent changes to directory information being visible to the filesystem object. Consequently it is best used only in a fairly limited scope where you don’t expected anything on the filesystem to change.
- __init__(wrap_fs: _F) None[source]¶
Create a filesystem. See help(type(self)) for accurate signature.
- getinfo(path: Text, namespaces: Collection[Text] | None = None) Info[source]¶
Get information about a resource on a filesystem.
- Parameters:
path (str) – A path to a resource on the filesystem.
namespaces (list, optional) – Info namespaces to query. The
"basic"namespace is alway included in the returned info, whatever the value ofnamespacesmay be.
- Returns:
resource information object.
- Return type:
- Raises:
fs.errors.ResourceNotFound – If
pathdoes not exist.
For more information regarding resource information, see Resource Info.
- isdir(path: Text) bool[source]¶
Check if a path maps to an existing directory.
- Parameters:
path (str) – A path on the filesystem.
- Returns:
Trueifpathmaps to a directory.- Return type:
bool
- isfile(path: Text) bool[source]¶
Check if a path maps to an existing file.
- Parameters:
path (str) – A path on the filesystem.
- Returns:
Trueifpathmaps to a file.- Return type:
bool
- scandir(path: Text, namespaces: Collection[Text] | None = None, page: Tuple[int, int] | None = None) Iterator[Info][source]¶
Get an iterator of resource info.
- Parameters:
path (str) – A path to a directory on the filesystem.
namespaces (list, optional) – A list of namespaces to include in the resource information, e.g.
['basic', 'access'].page (tuple, optional) – May be a tuple of
(<start>, <end>)indexes to return an iterator of a subset of the resource info, orNoneto iterate over the entire directory. Paging a directory scan may be necessary for very large directories.
- Returns:
an iterator of
Infoobjects.- Return type:
Iterator
- Raises:
fs.errors.DirectoryExpected – If
pathis not a directory.fs.errors.ResourceNotFound – If
pathdoes not exist.
- class fs.wrap.WrapReadOnly(wrap_fs: _F)[source]¶
Makes a Filesystem read-only.
Any call that would would write data or modify the filesystem in any way will raise a
ResourceReadOnlyexception.- appendbytes(path: Text, data: bytes) None[source]¶
Append bytes to the end of a file, creating it if needed.
- Parameters:
path (str) – Path to a file.
data (bytes) – Bytes to append.
- Raises:
TypeError – If
datais not abytesinstance.fs.errors.ResourceNotFound – If a parent directory of
pathdoes not exist.
- appendtext(path: Text, text: Text, encoding: Text = 'utf-8', errors: Text | None = None, newline: Text = '') None[source]¶
Append text to the end of a file, creating it if needed.
- Parameters:
path (str) – Path to a file.
text (str) – Text to append.
encoding (str) – Encoding for text files (defaults to
utf-8).errors (str, optional) – What to do with unicode decode errors (see
codecsmodule for more information).newline (str) – Newline parameter.
- Raises:
TypeError – if
textis not an unicode string.fs.errors.ResourceNotFound – if a parent directory of
pathdoes not exist.
- copy(src_path: Text, dst_path: Text, overwrite: bool = False, preserve_time: bool = False) None[source]¶
Copy file contents from
src_pathtodst_path.- Parameters:
src_path (str) – Path of source file.
dst_path (str) – Path to destination file.
overwrite (bool) – If
True, overwrite the destination file if it exists (defaults toFalse).preserve_time (bool) – If
True, try to preserve mtime of the resource (defaults toFalse).
- Raises:
fs.errors.DestinationExists – If
dst_pathexists, andoverwriteisFalse.fs.errors.ResourceNotFound – If a parent directory of
dst_pathdoes not exist.fs.errors.FileExpected – If
src_pathis not a file.
- create(path: Text, wipe: bool = False) bool[source]¶
Create an empty file.
The default behavior is to create a new file if one doesn’t already exist. If
wipeisTrue, any existing file will be truncated.- Parameters:
path (str) – Path to a new file in the filesystem.
wipe (bool) – If
True, truncate any existing file to 0 bytes (defaults toFalse).
- Returns:
Trueif a new file had to be created.- Return type:
bool
- getmeta(namespace: Text = 'standard') Mapping[Text, object][source]¶
Get meta information regarding a filesystem.
- Parameters:
namespace (str) – The meta namespace (defaults to
"standard").- Returns:
the meta information.
- Return type:
dict
Meta information is associated with a namespace which may be specified with the
namespaceparameter. The default namespace,"standard", contains common information regarding the filesystem’s capabilities. Some filesystems may provide other namespaces which expose less common or implementation specific information. If a requested namespace is not supported by a filesystem, then an empty dictionary will be returned.The
"standard"namespace supports the following keys:key
Description
case_insensitive
Trueif this filesystem is case insensitive.invalid_path_chars
A string containing the characters that may not be used on this filesystem.
max_path_length
Maximum number of characters permitted in a path, or
Nonefor no limit.max_sys_path_length
Maximum number of characters permitted in a sys path, or
Nonefor no limit.network
Trueif this filesystem requires a network.read_only
Trueif this filesystem is read only.supports_rename
Trueif this filesystem supports anos.renameoperation.Most builtin filesystems will provide all these keys, and third- party filesystems should do so whenever possible, but a key may not be present if there is no way to know the value.
Note
Meta information is constant for the lifetime of the filesystem, and may be cached.
- makedir(path: Text, permissions: Permissions | None = None, recreate: bool = False) SubFS[_W][source]¶
Make a directory.
- Parameters:
path (str) – Path to directory from root.
permissions (Permissions, optional) – a
Permissionsinstance, orNoneto use default.recreate (bool) – Set to
Trueto avoid raising an error if the directory already exists (defaults toFalse).
- Returns:
a filesystem whose root is the new directory.
- Return type:
- Raises:
fs.errors.DirectoryExists – If the path already exists.
fs.errors.ResourceNotFound – If the path is not found.
- makedirs(path: Text, permissions: Permissions | None = None, recreate: bool = False) SubFS[_W][source]¶
Make a directory, and any missing intermediate directories.
- Parameters:
path (str) – Path to directory from root.
permissions (Permissions, optional) – Initial permissions, or
Noneto use defaults.recreate (bool) – If
False(the default), attempting to create an existing directory will raise an error. Set toTrueto ignore existing directories.
- Returns:
A sub-directory filesystem.
- Return type:
- Raises:
fs.errors.DirectoryExists – if the path is already a directory, and
recreateisFalse.fs.errors.DirectoryExpected – if one of the ancestors in the path is not a directory.
- move(src_path: Text, dst_path: Text, overwrite: bool = False, preserve_time: bool = False) None[source]¶
Move a file from
src_pathtodst_path.- Parameters:
src_path (str) – A path on the filesystem to move.
dst_path (str) – A path on the filesystem where the source file will be written to.
overwrite (bool) – If
True, destination path will be overwritten if it exists.preserve_time (bool) – If
True, try to preserve mtime of the resources (defaults toFalse).
- Raises:
fs.errors.FileExpected – If
src_pathmaps to a directory instead of a file.fs.errors.DestinationExists – If
dst_pathexists, andoverwriteisFalse.fs.errors.ResourceNotFound – If a parent directory of
dst_pathdoes not exist.
- open(path: Text, mode: Text = 'r', buffering: int = -1, encoding: Text | None = None, errors: Text | None = None, newline: Text = '', line_buffering: bool = False, **options: Any) IO[source]¶
Open a file.
- Parameters:
path (str) – A path to a file on the filesystem.
mode (str) – Mode to open the file object with (defaults to r).
buffering (int) – Buffering policy (-1 to use default buffering, 0 to disable buffering, 1 to select line buffering, of any positive integer to indicate a buffer size).
encoding (str) – Encoding for text files (defaults to
utf-8)errors (str, optional) – What to do with unicode decode errors (see
codecsmodule for more information).newline (str) – Newline parameter.
**options – keyword arguments for any additional information required by the filesystem (if any).
- Returns:
a file-like object.
- Return type:
io.IOBase
- Raises:
fs.errors.FileExpected – If the path is not a file.
fs.errors.FileExists – If the file exists, and exclusive mode is specified (
xin the mode).fs.errors.ResourceNotFound – If the path does not exist.
- openbin(path: Text, mode: Text = 'r', buffering: int = -1, **options: Any) BinaryIO[source]¶
Open a binary file-like object.
- Parameters:
path (str) – A path on the filesystem.
mode (str) – Mode to open file (must be a valid non-text mode, defaults to r). Since this method only opens binary files, the
bin the mode string is implied.buffering (int) – Buffering policy (-1 to use default buffering, 0 to disable buffering, or any positive integer to indicate a buffer size).
**options – keyword arguments for any additional information required by the filesystem (if any).
- Returns:
a file-like object.
- Return type:
io.IOBase
- Raises:
fs.errors.FileExpected – If
pathexists and is not a file.fs.errors.FileExists – If the
pathexists, and exclusive mode is specified (xin the mode).fs.errors.ResourceNotFound – If
pathdoes not exist andmodedoes not imply creating the file, or if any ancestor ofpathdoes not exist.
- remove(path: Text) None[source]¶
Remove a file from the filesystem.
- Parameters:
path (str) – Path of the file to remove.
- Raises:
fs.errors.FileExpected – If the path is a directory.
fs.errors.ResourceNotFound – If the path does not exist.
- removedir(path: Text) None[source]¶
Remove a directory from the filesystem.
- Parameters:
path (str) – Path of the directory to remove.
- Raises:
fs.errors.DirectoryNotEmpty – If the directory is not empty ( see
removetreefor a way to remove the directory contents).fs.errors.DirectoryExpected – If the path does not refer to a directory.
fs.errors.ResourceNotFound – If no resource exists at the given path.
fs.errors.RemoveRootError – If an attempt is made to remove the root directory (i.e.
'/')
- removetree(path: Text) None[source]¶
Recursively remove a directory and all its contents.
This method is similar to
removedir, but will remove the contents of the directory if it is not empty.- Parameters:
dir_path (str) – Path to a directory on the filesystem.
- Raises:
fs.errors.ResourceNotFound – If
dir_pathdoes not exist.fs.errors.DirectoryExpected – If
dir_pathis not a directory.
Caution
A filesystem should never delete its root folder, so
FS.removetree("/")has different semantics: the contents of the root folder will be deleted, but the root will be untouched:>>> home_fs = fs.open_fs("~") >>> home_fs.removetree("/") >>> home_fs.exists("/") True >>> home_fs.isempty("/") True
Combined with
opendir, this can be used to clear a directory without removing the directory itself:>>> home_fs = fs.open_fs("~") >>> home_fs.opendir("/Videos").removetree("/") >>> home_fs.exists("/Videos") True >>> home_fs.isempty("/Videos") True
- setinfo(path: Text, info: RawInfo) None[source]¶
Set info on a resource.
This method is the complement to
getinfoand is used to set info values on a resource.- Parameters:
path (str) – Path to a resource on the filesystem.
info (dict) – Dictionary of resource info.
- Raises:
fs.errors.ResourceNotFound – If
pathdoes not exist on the filesystem
The
infodict should be in the same format as the raw info returned bygetinfo(file).raw.Example
>>> details_info = {"details": { ... "modified": time.time() ... }} >>> my_fs.setinfo('file.txt', details_info)
- settimes(path: Text, accessed: datetime | None = None, modified: datetime | None = None) None[source]¶
Set the accessed and modified time on a resource.
- Parameters:
path – A path to a resource on the filesystem.
accessed (datetime, optional) – The accessed time, or
None(the default) to use the current time.modified (datetime, optional) – The modified time, or
None(the default) to use the same time as theaccessedparameter.
- touch(path: Text) None[source]¶
Touch a file on the filesystem.
Touching a file means creating a new file if
pathdoesn’t exist, or update accessed and modified times if the path does exist. This method is similar to the linux command of the same name.- Parameters:
path (str) – A path to a file on the filesystem.
- upload(path: Text, file: BinaryIO, chunk_size: int | None = None, **options: Any) None[source]¶
Set a file to the contents of a binary file object.
This method copies bytes from an open binary file to a file on the filesystem. If the destination exists, it will first be truncated.
- Parameters:
path (str) – A path on the filesystem.
file (io.IOBase) – a file object open for reading in binary mode.
chunk_size (int, optional) – Number of bytes to read at a time, if a simple copy is used, or
Noneto use sensible default.**options – Implementation specific options required to open the source file.
- Raises:
fs.errors.ResourceNotFound – If a parent directory of
pathdoes not exist.
Note that the file object
filewill not be closed by this method. Take care to close it after this method completes (ideally with a context manager).Example
>>> with open('~/movies/starwars.mov', 'rb') as read_file: ... my_fs.upload('starwars.mov', read_file)
- writebytes(path: Text, contents: bytes) None[source]¶
Copy binary data to a file.
- Parameters:
path (str) – Destination path on the filesystem.
contents (bytes) – Data to be written.
- Raises:
TypeError – if contents is not bytes.
- writefile(path: Text, file: IO, encoding: Text | None = None, errors: Text | None = None, newline: Text = '') None[source]¶
Set a file to the contents of a file object.
- Parameters:
path (str) – A path on the filesystem.
file (io.IOBase) – A file object open for reading.
encoding (str, optional) – Encoding of destination file, defaults to
Nonefor binary.errors (str, optional) – How encoding errors should be treated (same as
io.open).newline (str) – Newline parameter (same as
io.open).
This method is similar to
upload, in that it copies data from a file-like object to a resource on the filesystem, but unlikeupload, this method also supports creating files in text-mode (if theencodingargument is supplied).Note that the file object
filewill not be closed by this method. Take care to close it after this method completes (ideally with a context manager).Example
>>> with open('myfile.txt') as read_file: ... my_fs.writefile('myfile.txt', read_file)
- writetext(path: Text, contents: Text, encoding: Text = 'utf-8', errors: Text | None = None, newline: Text = '') None[source]¶
Create or replace a file with text.
- Parameters:
path (str) – Destination path on the filesystem.
contents (str) – Text to be written.
encoding (str, optional) – Encoding of destination file (defaults to
'utf-8').errors (str, optional) – How encoding errors should be treated (same as
io.open).newline (str) – Newline parameter (same as
io.open).
- Raises:
TypeError – if
contentsis not a unicode string.
- fs.wrap.cache_directory(fs: _T) WrapCachedDir[_T][source]¶
Make a filesystem that caches directory information.
- fs.wrap.read_only(fs: _T) WrapReadOnly[_T][source]¶
Make a read-only filesystem.