xattr: Extended Filesystem Attributes

1.3.0 · active · verified Sat Apr 11

xattr is a Python wrapper for extended filesystem attributes, allowing programmatic access to name-data pairs associated with files and directories. It supports listing, getting, setting, and removing these attributes. The library is actively maintained, with several releases per year, and is currently at version 1.3.0.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set, list, get, and remove extended attributes on a file using `xattr`'s dict-like interface and helper methods. It handles potential `EnvironmentError` if extended attributes are not supported on the system.

import xattr
import os

# Create a dummy file
file_path = "test_file.txt"
with open(file_path, "w") as f:
    f.write("Hello, extended attributes!")

try:
    # Use the dict-like interface to set an attribute
    file_xattr = xattr.xattr(file_path)
    file_xattr["user.comment"] = b"This is a test comment"
    file_xattr["user.tag"] = b"important"

    print(f"Set 'user.comment' and 'user.tag' on {file_path}")

    # List all attributes
    attributes = file_xattr.list()
    print(f"All attributes: {attributes}")

    # Get a specific attribute
    comment = file_xattr.get("user.comment")
    print(f"'user.comment': {comment.decode('utf-8')}")

    # Check if an attribute exists
    if "user.tag" in file_xattr:
        print(f"'user.tag' exists, value: {file_xattr['user.tag'].decode('utf-8')}")

    # Remove an attribute
    file_xattr.remove("user.tag")
    print("Removed 'user.tag'")

    attributes_after_removal = file_xattr.list()
    print(f"Attributes after removal: {attributes_after_removal}")

except EnvironmentError as e:
    print(f"Error accessing extended attributes: {e}")
    print("Extended attributes may not be supported on this filesystem or OS.")
finally:
    if os.path.exists(file_path):
        os.remove(file_path)
        print(f"Cleaned up {file_path}")

view raw JSON →