PyFilesystem2

2.4.16 · active · verified Thu Apr 09

PyFilesystem2 is a Python library that provides a common, high-level abstraction layer for interacting with various filesystems, including local, memory, zip, FTP, and more. It enables consistent management of files and directories across different storage backends. The current version is 2.4.16, with frequent maintenance and minor feature releases.

Warnings

Install

Imports

Quickstart

Demonstrates opening and interacting with a memory filesystem and a local OS filesystem. It shows creating, writing, reading, listing, and cleaning up resources, emphasizing the use of context managers for proper resource handling.

from fs import open_fs
from fs.osfs import OSFS
import os

# Example 1: Using a memory filesystem
print("--- Memory Filesystem Example ---")
with open_fs("mem://") as mem_fs:
    mem_fs.writetext("hello.txt", "Hello from MemoryFS!")
    print(f"Content of hello.txt: {mem_fs.readtext('hello.txt')}")
    print(f"Files in memory FS: {mem_fs.listdir('/')}")

# Example 2: Using the local operating system filesystem
print("\n--- OS Filesystem Example ---")
# Opens a filesystem for the current working directory
with OSFS('.') as os_fs:
    temp_dir_path = "_fs_temp_dir_"
    temp_file_path = os.path.join(temp_dir_path, "temp_quickstart.txt")

    if not os_fs.exists(temp_dir_path):
        os_fs.makedir(temp_dir_path)
        print(f"Created directory: {temp_dir_path}")

    os_fs.writetext(temp_file_path, "This is a temporary file in OSFS.")
    print(f"Content of {temp_file_path}: {os_fs.readtext(temp_file_path)}")

    # Clean up the created file and directory
    os_fs.remove(temp_file_path)
    os_fs.removedir(temp_dir_path)
    print(f"Cleaned up: {temp_file_path} and {temp_dir_path}")

view raw JSON →