PyFilesystem2
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
- breaking PyFilesystem v1 (pyfilesystem) vs. v2 (fs) - Complete API and import path rewrite.
- gotcha Filesystem objects should be properly closed using context managers or explicit close() calls.
- gotcha Paths within PyFilesystem are 'universal' and use `/` as the separator, regardless of the underlying OS.
- gotcha Attempting write operations on a read-only filesystem will raise errors.
Install
-
pip install fs
Imports
- open_fs
from fs import open_fs
- OSFS
from fs.osfs import OSFS
- MemoryFS
from fs.memoryfs import MemoryFS
- FS
from fs.base import FS
Quickstart
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}")