### Open FTPFS and List Directory (Python) Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/guide.rst Shows how to connect to an FTP server and list the contents of its root directory using the FTPFS class. This requires the 'ftpfs' library to be installed. ```python >>> from ftpfs import FTPFS >>> debian_fs = FTPFS('ftp.mirror.nl') >>> debian_fs.listdir('/') ['debian-archive', 'debian-backports', 'debian', 'pub', 'robots.txt'] ``` -------------------------------- ### Basic FileSystem Test Suite Setup (Python) Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/implementers.rst Provides a minimal example of how to set up a test case for a custom filesystem class using PyFilesystem's `FSTestCases`. This involves inheriting from `FSTestCases` and `unittest.TestCase`, and implementing the `make_fs` method to return an instance of the filesystem to be tested. ```python import unittest from fs.test import FSTestCases class TestMyFS(FSTestCases, unittest.TestCase): def make_fs(self): # Return an instance of your FS object here return MyFS() ``` -------------------------------- ### Manually Registering a Filesystem Opener in Python Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/openers.rst Shows how to manually install a custom filesystem opener into the `fs.opener.registry`. This is useful when entry points are not available or extensions are loaded after the interpreter starts. It requires importing the opener class and then calling `fs.opener.registry.install`. ```python import fs.opener from fs_s3fs.opener import S3FSOpener fs.opener.registry.install(S3FSOpener) # fs.open_fs("s3fs://...") should now work ``` -------------------------------- ### Install Documentation Dependencies Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/CONTRIBUTING.md Installs the required Python packages for building the project's documentation from 'docs/requirements.txt' using pip. ```shell pip install -r docs/requirements.txt ``` -------------------------------- ### Opening and Reading Files with open in Python Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/guide.rst Demonstrates how to open a file for reading using the `open` method on a PyFilesystem object, similar to Python's built-in `io.open`. This example reads the content of 'reminder.txt'. ```python >>> with open_fs('~/') as home_fs: ... with home_fs.open('reminder.txt') as reminder_file: ... print(reminder_file.read()) buy coffee ``` -------------------------------- ### Glob Filesystem for Pattern Matching Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/guide.rst Demonstrates using glob patterns to find and manipulate files within a filesystem. This example shows how to remove all `.pyc` files from a project directory using the `glob` method. ```python from fs import open_fs project_fs = open_fs('~/project') project_fs.glob('**/*.pyc').remove() ``` -------------------------------- ### Open OSFS using open_fs (Python) Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/guide.rst Illustrates opening an OSFS filesystem from a URL-like string using the `open_fs` function. This method is more general and useful for configuration-driven filesystem access. ```python >>> from fs import open_fs >>> home_fs = open_fs('osfs://~/') >>> home_fs.listdir('/') ['world domination.doc', 'paella-recipe.txt', 'jokes.txt', 'projects'] ``` -------------------------------- ### Open OSFS and List Directory (Python) Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/guide.rst Demonstrates how to open an Operating System File System (OSFS) object representing the user's home directory and list its contents. This utilizes the OSFS class for direct instantiation. ```python >>> from fs.osfs import OSFS >>> home_fs = OSFS("~/") >>> home_fs.listdir('/') ['world domination.doc', 'paella-recipe.txt', 'jokes.txt', 'projects'] ``` -------------------------------- ### Install Test Dependencies with Pip Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/CONTRIBUTING.md Installs the necessary Python packages for running tests from the 'tests/requirements.txt' file. This is an alternative to using tox for dependency management. ```shell pip install -r tests/requirements.txt ``` -------------------------------- ### Listing Directory Contents with listdir in Python Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/guide.rst Shows how to use the `listdir` method to get a list of file and directory names within a specified path. This method is similar to `os.listdir`. ```python >>> home_fs.listdir('/projects') ['fs', 'moya', 'README.md'] ``` -------------------------------- ### Get File Information with PyFilesystem Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/info.rst Demonstrates how to retrieve basic and detailed information about a file using PyFilesystem. It initializes an OSFS filesystem, writes text to a file, and then fetches its info including name, directory status, and size. ```python from fs.osfs import OSFS fs = OSFS('.') fs.writetext('example.txt', 'Hello, World!') info = fs.getinfo('example.txt', namespaces=['details']) print(info.name) print(info.is_dir) print(info.size) ``` -------------------------------- ### Copy Filesystem with Explicit FS Objects Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/guide.rst Shows an alternative way to copy filesystem contents by explicitly defining the source and destination filesystem objects, such as `OSFS` and `ZipFS`. ```python from fs.copy import copy_fs from fs.osfs import OSFS from fs.zipfs import ZipFS copy_fs(OSFS('~/projects'), ZipFS('projects.zip')) ``` -------------------------------- ### Print Filesystem Tree (Python) Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/guide.rst Shows how to use the `tree()` method on a filesystem object to display an ASCII representation of its directory structure. This is helpful for debugging and visualizing the filesystem hierarchy. ```python >>> from fs import open_fs >>> my_fs = open_fs('.') >>> my_fs.tree() ├── locale │ └── readme.txt ├── logic │ ├── content.xml │ ├── data.xml │ ├── mountpoints.xml │ └── readme.txt ├── lib.ini └── readme.txt ``` -------------------------------- ### Calculate Total Bytes of Python Code (Python) Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/walking.rst This example calculates the total number of bytes occupied by Python code files within a user's home directory. It uses walk.info() with the 'details' namespace to get file size information and sums it up for non-directory entries. ```Python from fs import open_fs home_fs = open_fs('~/projects') bytes_of_python = sum( info.size for info in home_fs.walk.info(namespaces=['details']) if not info.is_dir ) ``` -------------------------------- ### Get All Directory Paths with Walk Dirs Method (Python) Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/walking.rst This example shows how to get an iterable of directory paths using the walk.dirs() method on a filesystem object. This method specifically returns paths to directories, ignoring files within the traversal. ```Python from fs import open_fs home_fs = open_fs('~/projects') for dir_path in home_fs.walk.dirs(): print("{!r} contains sub-directory {}".format(home_fs, dir_path)) ``` -------------------------------- ### Creating Sub-directories and Files with makedirs in Python Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/guide.rst Shows how to create nested directories using `makedirs` and then create files within those new directories using `touch` and `writetext`. `makedirs` returns a `SubFS` object for the newly created directory. ```python >>> home_fs = open_fs('~/') >>> game_fs = home_fs.makedirs('projects/game') >>> game_fs.touch('__init__.py') >>> game_fs.writetext('README.md', "Tetris clone") >>> game_fs.listdir('/') ['__init__.py', 'README.md'] ``` -------------------------------- ### Close Filesystem Explicitly (Python) Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/guide.rst Provides an example of explicitly closing a filesystem object after use. This ensures that any resources held by the filesystem are properly released, which is important for certain filesystem types. ```python >>> home_fs = open_fs('osfs://~/') >>> home_fs.writetext('reminder.txt', 'buy coffee') >>> home_fs.close() ``` -------------------------------- ### Open Current Directory using open_fs (Python) Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/guide.rst Demonstrates opening the current working directory as an OSFS using `open_fs` without specifying a protocol, which defaults to OSFS. This is a convenient shorthand for accessing local files. ```python >>> from fs import open_fs >>> home_fs = open_fs('.') >>> home_fs.listdir('/') ['world domination.doc', 'paella-recipe.txt', 'jokes.txt', 'projects'] ``` -------------------------------- ### Walk Directory for Specific Files Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/guide.rst Shows how to recursively traverse a directory structure and list files matching a specific pattern, such as Python files. This utilizes the `walk` attribute of an FS object. ```python from fs import open_fs home_fs = open_fs('~/') for path in home_fs.walk.files(filter=['*.py']): print(path) ``` -------------------------------- ### Using FS Objects as Context Managers in Python Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/guide.rst Demonstrates how to use PyFilesystem objects as context managers to ensure filesystems are automatically closed. This is the recommended practice for managing FS resources. ```python >>> with open_fs('osfs://~/') as home_fs: ... home_fs.writetext('reminder.txt', 'buy coffee') ``` -------------------------------- ### Get Path and Info Objects with Walk Info Method (Python) Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/walking.rst This snippet demonstrates using the walk.info() method to get a generator of tuples, where each tuple contains a path and its corresponding fs.info.Info object. This allows checking if a path refers to a directory or file using the info.is_dir attribute. ```Python from fs import open_fs home_fs = open_fs('~/projects') for path, info in home_fs.walk.info(): if info.is_dir: print("[dir] {}".format(path)) else: print("[file] {}".format(path)) ``` -------------------------------- ### Copy Specific Files Using Walker Filter Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/guide.rst Demonstrates how to use a `Walker` object with a filter to copy only specific types of files (e.g., Python files) from a source to a destination filesystem. ```python from fs.copy import copy_fs from fs.walk import Walker copy_fs('~/projects', 'zip://projects.zip', walker=Walker(filter=['*.py'])) ``` -------------------------------- ### Copy Filesystem Contents to Zip Archive Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/guide.rst Illustrates copying the contents of one filesystem (e.g., a local directory) to another destination, such as a zip archive. This uses the `copy_fs` function from the `fs.copy` module. ```python from fs.copy import copy_fs copy_fs('~/projects', 'zip://projects.zip') ``` -------------------------------- ### Walk Files Recursively Using FS Object Walk Attribute (Python) Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/walking.rst This example shows a more concise way to recursively walk a filesystem and print Python file paths by using the 'walk' attribute directly on the filesystem object. This approach avoids explicit instantiation of the Walker class, leveraging the BoundWalker object associated with the filesystem. ```Python from fs import open_fs home_fs = open_fs('~/projects') for path in home_fs.walk.files(filter=['*.py']): print(path) ``` -------------------------------- ### Thread-Safe FileSystem Method Example (Python) Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/implementers.rst Demonstrates how to ensure thread safety in a PyFilesystem implementation by using the `_lock` attribute as a context manager. This pattern prevents race conditions when multiple threads access the filesystem methods concurrently. ```python with self._lock: do_something() ``` -------------------------------- ### Filtering Directory Contents with filterdir in Python Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/guide.rst Illustrates how to use the `filterdir` method to list directory contents based on wildcard patterns and optional namespaces for additional details. This method extends `scandir` functionality. ```python >>> code_fs = OSFS('~/projects/src') >>> directory = list(code_fs.filterdir('/', files=['*.py'])) ``` -------------------------------- ### Write File Contents as Bytes and Text Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/guide.rst Illustrates writing data to files as raw bytes or encoded text using PyFilesystem2's convenient methods. Similar to reading, these methods simplify the writing process and may leverage optimized implementations. ```python from fs import open_fs my_fs = open_fs('~/my_files') # Write bytes my_fs.writebytes('output.bin', b'\x01\x02\x03') # Write text (encoded as UTF-8 by default) my_fs.writetext('log.txt', 'This is a log message.') ``` -------------------------------- ### Listing Directory Contents with scandir in Python Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/guide.rst Demonstrates the use of `scandir` to obtain an iterable of `Info` objects, providing more detailed information than `listdir`. The `Info` objects contain attributes like `is_dir` and can include details such as size and modification time if requested. ```python >>> directory = list(home_fs.scandir('/projects')) >>> directory [, , ] ``` ```python >>> directory = code_fs.filterdir('/', files=['*.py'], namespaces=['details']) >>> sum(info.size for info in directory) ``` -------------------------------- ### Read File Contents as Bytes and Text Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/guide.rst Demonstrates reading file contents directly as bytes or decoded text using PyFilesystem2's optimized methods. These methods bypass the need for explicit file opening and can offer performance benefits. ```python from fs import open_fs my_fs = open_fs('~/my_files') # Read as bytes file_bytes = my_fs.readbytes('data.bin') # Read as text (decoded as UTF-8 by default) file_text = my_fs.readtext('config.txt') ``` -------------------------------- ### Get OS System Path - Python Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/concepts.rst Retrieves the operating system's absolute path for a given PyFilesystem path. This is crucial for modules that require OS-level path compatibility. It converts a path within the FS context to an OS-understood format. Raises `NoSysPath` if the filesystem does not map to a system path. ```python from fs.osfs import OSFS home_fs = OSFS('~/') system_path = home_fs.getsyspath('test.txt') print(system_path) ``` -------------------------------- ### Configure setup.py for PyFilesystem Extension Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/extension.rst This Python script demonstrates a minimal setup.py file for a PyFilesystem2 extension. It specifies package metadata, dependencies (including PyFilesystem itself with version pinning), and crucial entry points for registering the filesystem opener. This ensures proper discovery and integration with PyFilesystem. ```python from setuptools import setup setup( name='fs-awesomefs', # Name in PyPi author="You !", author_email="your.email@domain.ext", description="An awesome filesystem for pyfilesystem2 !", install_requires=[ "fs~=2.0.5" ], entry_points = { 'fs.opener': [ 'awe = awesomefs.opener:AwesomeFSOpener', ] }, license="MY LICENSE", packages=['awesomefs'], version="X.Y.Z", ) ``` -------------------------------- ### Create MultiFS for Theming - Python Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/reference/multifs.rst Demonstrates how to create a MultiFS to combine 'templates' and 'theme' directories for file overriding. It uses OSFS to wrap the actual directories and MultiFS to manage the overlay. Files are loaded from 'theme' first, then 'templates'. ```python from fs.osfs import OSFS from fs.multifs import MultiFS theme_fs = MultiFS() theme_fs.add_fs('templates', OSFS('templates')) theme_fs.add_fs('theme', OSFS('theme')) ``` -------------------------------- ### Build Sphinx Documentation Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/CONTRIBUTING.md Builds the HTML documentation for the project using Sphinx. The output is placed in the 'build/sphinx/html/' directory. ```shell python setup.py build_sphinx ``` -------------------------------- ### Implement S3FSOpener for S3 Filesystem Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/extension.rst This Python code defines an Opener class for an S3 filesystem. It handles parsing S3 FS URLs, extracting bucket names and credentials, and instantiating the S3FS class. This allows S3 filesystems to be opened using FS URLs. ```python from fs.opener import Opener from fs.opener.errors import OpenerError from ._s3fs import S3FS class S3FSOpener(Opener): protocols = ['s3'] def open_fs(self, fs_url, parse_result, writeable, create, cwd): bucket_name, _, dir_path = parse_result.resource.partition('/') if not bucket_name: raise OpenerError( "invalid bucket name in '{}'".format(fs_url) ) s3fs = S3FS( bucket_name, dir_path=dir_path or '/', aws_access_key_id=parse_result.username or None, aws_secret_access_key=parse_result.password or None, ) return s3fs ``` -------------------------------- ### Opening a Filesystem with an FS URL in Python Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/openers.rst Demonstrates how to open a filesystem using an FS URL string with the `open_fs` function from the `fs` library. This is the primary method for interacting with filesystems specified by URLs. ```python from fs import open_fs projects_fs = open_fs('osfs://~/projects') ``` -------------------------------- ### Discover and Run Unit Tests Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/CONTRIBUTING.md Discovers and runs all unit tests using Python's built-in unittest module. This method is used when tox is not available or preferred for test execution. ```shell python -m unittest discover -vv ``` -------------------------------- ### PyFilesystem2 Core Methods Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/interface.rst This section details the core methods available on PyFilesystem objects for common file and directory operations. ```APIDOC ## PyFilesystem2 Core Methods ### Description Provides a comprehensive list of methods for interacting with files and directories within a filesystem object. ### Method Various (refer to individual method descriptions) ### Endpoint N/A (These are object methods, not API endpoints) ### Parameters N/A (Parameters are specific to each method) ### Request Example N/A ### Response N/A --- ## appendbytes /fs/base/FS.appendbytes ### Description Appends bytes to a file. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## appendtext /fs/base/FS.appendtext ### Description Appends text to a file. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## check /fs/base/FS.check ### Description Checks if a filesystem is open or raises an error. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## close /fs/base/FS.close ### Description Closes the filesystem. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## copy /fs/base/FS.copy ### Description Copies a file to another location. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## copydir /fs/base/FS.copydir ### Description Copies a directory to another location. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## create /fs/base/FS.create ### Description Creates or truncates a file. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## desc /fs/base/FS.desc ### Description Gets a description of a resource. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## download /fs/base/FS.download ### Description Copies a file on the filesystem to a file-like object. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## exists /fs/base/FS.exists ### Description Checks if a path exists. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## filterdir /fs/base/FS.filterdir ### Description Iterates resources, filtering by wildcard(s). ### Method N/A (Method on FS object) ### Endpoint N/A --- ## getbasic /fs/base/FS.getbasic ### Description Gets basic info namespace for a resource. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## getdetails /fs/base/FS.getdetails ### Description Gets details info namespace for a resource. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## getinfo /fs/base/FS.getinfo ### Description Gets info regarding a file or directory. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## getmeta /fs/base/FS.getmeta ### Description Gets meta information for a resource. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## getmodified /fs/base/FS.getmodified ### Description Gets the last modified time of a resource. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## getospath /fs/base/FS.getospath ### Description Gets path with encoding expected by the OS. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## getsize /fs/base/FS.getsize ### Description Gets the size of a file. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## getsyspath /fs/base/FS.getsyspath ### Description Gets the system path of a resource, if one exists. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## gettype /fs/base/FS.gettype ### Description Gets the type of a resource. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## geturl /fs/base/FS.geturl ### Description Gets a URL to a resource, if one exists. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## hassyspath /fs/base/FS.hassyspath ### Description Checks if a resource maps to the OS filesystem. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## hash /fs/base/FS.hash ### Description Gets the hash of a file's contents. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## hasurl /fs/base/FS.hasurl ### Description Checks if a resource has a URL. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## isclosed /fs/base/FS.isclosed ### Description Checks if the filesystem is closed. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## isempty /fs/base/FS.isempty ### Description Checks if a directory is empty. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## isdir /fs/base/FS.isdir ### Description Checks if path maps to a directory. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## isfile /fs/base/FS.isfile ### Description Checks if path maps to a file. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## islink /fs/base/FS.islink ### Description Checks if path is a link. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## listdir /fs/base/FS.listdir ### Description Gets a list of resources in a directory. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## lock /fs/base/FS.lock ### Description Gets a thread lock context manager. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## makedir /fs/base/FS.makedir ### Description Makes a directory. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## makedirs /fs/base/FS.makedirs ### Description Makes a directory and intermediate directories. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## match /fs/base/FS.match ### Description Matches one or more wildcard patterns against a path. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## move /fs/base/FS.move ### Description Moves a file to another location. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## movedir /fs/base/FS.movedir ### Description Moves a directory to another location. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## open /fs/base/FS.open ### Description Opens a file on the filesystem. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## openbin /fs/base/FS.openbin ### Description Opens a binary file. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## opendir /fs/base/FS.opendir ### Description Gets a filesystem object for a directory. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## readbytes /fs/base/FS.readbytes ### Description Reads a file as bytes. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## readtext /fs/base/FS.readtext ### Description Reads a file as text. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## remove /fs/base/FS.remove ### Description Removes a file. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## removedir /fs/base/FS.removedir ### Description Removes a directory. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## removetree /fs/base/FS.removetree ### Description Recursively removes files and directories. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## scandir /fs/base/FS.scandir ### Description Scans files and directories. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## setinfo /fs/base/FS.setinfo ### Description Sets resource information. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## settimes /fs/base/FS.settimes ### Description Sets modified times for a resource. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## touch /fs/base/FS.touch ### Description Creates a file or updates its times. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## tree /fs/base/FS.tree ### Description Renders a tree view of the filesystem. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## upload /fs/base/FS.upload ### Description Copies a binary file to the filesystem. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## validatepath /fs/base/FS.validatepath ### Description Checks if a path is valid and returns the normalized path. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## writebytes /fs/base/FS.writebytes ### Description Writes a file as bytes. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## writefile /fs/base/FS.writefile ### Description Writes a file-like object to the filesystem. ### Method N/A (Method on FS object) ### Endpoint N/A --- ## writetext /fs/base/FS.writetext ### Description Writes a file as text. ### Method N/A (Method on FS object) ### Endpoint N/A ``` -------------------------------- ### Iterate Directory Steps with Walk Method (Python) Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/walking.rst This code snippet demonstrates iterating through directory traversal steps using the walk() method on a filesystem object. Each step provides the current directory path, a list of sub-directory Info objects, and a list of file Info objects. ```Python from fs import open_fs home_fs = open_fs('~/projects') for step in home_fs.walk(filter=['*.py']): print('In dir {}'.format(step.path)) print('sub-directories: {!r}'.format(step.dirs)) print('files: {!r}'.format(step.files)) ``` -------------------------------- ### Requesting Multiple Namespaces in PyFilesystem Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/info.rst Shows how to request specific namespaces ('details' and 'access') when retrieving resource information. This allows fine-grained control over the data fetched for a file. ```python resource_info = fs.getinfo('myfile.txt', namespaces=['details', 'access']) ``` -------------------------------- ### Check Documentation Style Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/CONTRIBUTING.md Runs a check for the documentation style, specifically the docstrings, using the 'docstyle' tox environment. This ensures adherence to the Google docstring format. ```shell tox -e docstyle ``` -------------------------------- ### Run All Tox Environments Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/CONTRIBUTING.md Executes all defined test environments using the tox tool. This is a convenient way to ensure code compatibility across multiple Python versions and configurations. ```shell tox ``` -------------------------------- ### Mounting Filesystems with MountFS in Python Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/reference/mountfs.rst Demonstrates how to use the MountFS class from pyfilesystem2 to combine multiple filesystems. It creates a virtual filesystem where paths under specified mount points are directed to their respective underlying filesystems. Dependencies include the 'fs' library. The input consists of existing filesystem objects, and the output is a unified MountFS object. ```python from fs.mountfs import MountFS combined_fs = MountFS() combined_fs.mount('config', config_fs) combined_fs.mount('resources', resources_fs) print(combined_fs.gettext('/config/defaults.cfg')) read_jpg(combined_fs.open('/resources/images/logo.jpg', 'rb')) ``` -------------------------------- ### Check Code Formatting with Black Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/CONTRIBUTING.md Runs the 'black' code formatter to ensure consistent code style across the project. This command is executed within the 'codeformat' tox environment. ```shell tox -e codeformat ``` -------------------------------- ### Handling Missing Info Namespaces in Python Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/info.rst Demonstrates how to gracefully handle situations where a required namespace is not present in the file information. It shows both a try-except block for catching MissingInfoNamespace and a check using has_namespace. ```python from fs import errors try: print('user is {}'.format(info.user)) except errors.MissingInfoNamespace: # No 'access' namespace pass if info.has_namespace('access'): print('user is {}'.format(info.user)) ``` -------------------------------- ### Run Specific Tox Environment (Python 3.9) Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/CONTRIBUTING.md Runs tests using a specific tox environment, in this case, 'py39' for Python 3.9. This allows for faster iteration when testing against a particular Python version. ```shell tox -e py39 ``` -------------------------------- ### Walk Files Recursively with Walker Filter (Python) Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/walking.rst This snippet demonstrates how to recursively walk a filesystem and print the paths of all Python files. It utilizes the Walker class with a filter to specify the file pattern. The Walker object is instantiated with the filter and then used with the files() method on a bound filesystem object. ```Python from fs import open_fs from fs.walk import Walker home_fs = open_fs('~/projects') walker = Walker(filter=['*.py']) for path in walker.files(home_fs): print(path) ``` -------------------------------- ### Run Type Checking with Mypy Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/CONTRIBUTING.md Executes 'mypy' for static type checking, using type annotations written as comments for Python 2.7 compatibility. This is performed using the 'typecheck' tox environment. ```shell tox -e typecheck ``` -------------------------------- ### Iterate and Print Python Files using Glob Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/globbing.rst Demonstrates how to use the `glob` attribute to find all Python files recursively in a filesystem and print their paths and sizes. It returns an iterator of `GlobMatch` objects. ```python for match in my_fs.glob("**/*.py"): print(f"{match.path} is {match.info.size} bytes long") ``` -------------------------------- ### Open Subdirectory with Sandboxing - Python Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/concepts.rst Creates a new FS object that represents a subdirectory, effectively sandboxing operations to that specific directory. This is useful for passing FS objects to functions that should not have access to the parent filesystem. Operations on the returned FS object are relative to the subdirectory's root. ```python from fs.osfs import OSFS # Assuming 'foo' is a directory containing 'bar' foo_fs = OSFS('foo') bar_fs = foo_fs.opendir('bar') # Now, operations on bar_fs are relative to 'foo/bar' # For example, bar_fs.getsyspath('readme.txt') would resolve correctly print(bar_fs.getsyspath('readme.txt')) ``` -------------------------------- ### Count Python Lines of Code with Standard Library Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/README.md This function counts non-blank lines of Python code in a local directory using Python's standard `os` module. It demonstrates the traditional approach without filesystem abstraction, requiring manual handling of directory traversal and file paths. Dependencies include the `os` module. ```python import os def count_py_loc(path): """Count non-blank lines of Python code using standard library.""" count = 0 for root, dirs, files in os.walk(path): for name in files: if name.endswith('.py'): with open(os.path.join(root, name), 'rt') as python_file: count += sum(1 for line in python_file if line.strip()) return count # Example usage: # print(count_py_loc('/path/to/your/projects')) ``` -------------------------------- ### Count Python Lines of Code with PyFilesystem2 Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/README.md This function iterates through all `.py` files in a given filesystem (recursively) and counts the non-blank lines of code. It leverages PyFilesystem2's `walk.files` and `open` methods for a unified interface across different storage types. Dependencies include the `fs` library. ```python from fs import open_fs def count_python_loc(fs): """Count non-blank lines of Python code.""" count = 0 for path in fs.walk.files(filter=['*.py']): with fs.open(path) as python_file: count += sum(1 for line in python_file if line.strip()) return count # Example usage for local directory: projects_fs = open_fs('~/projects') print(count_python_loc(projects_fs)) # Example usage for a zip file: # projects_fs = open_fs('zip://projects.zip') # print(count_python_loc(projects_fs)) # Example usage for an FTP server: # projects_fs = open_fs('ftp://ftp.example.org/projects') # print(count_python_loc(projects_fs)) ``` -------------------------------- ### Check Code Style with Flake8 Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/CONTRIBUTING.md Invokes flake8, a tool for checking Python code style according to PEP8 guidelines, along with common plugins. This is typically run within a tox environment ('codestyle'). ```shell tox -e codestyle ``` -------------------------------- ### Remove .pyc Files Recursively using Glob Source: https://github.com/pyfilesystem/pyfilesystem2/blob/master/docs/source/globbing.rst Shows how to use the `glob` method combined with the `remove` method to efficiently delete all files matching a specific pattern (e.g., '.pyc' files) recursively within a directory. This operation returns the number of files removed. ```python import fs fs.open_fs('~/projects/my_project').glob('**/*.pyc').remove() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.