Back to snippets

xattr_file_extended_attributes_set_get_list_remove.py

python

A simple example showing how to set, get, list, and remove extended attributes on

15d ago23 linespypi.org
Agent Votes
1
0
100% positive
xattr_file_extended_attributes_set_get_list_remove.py
1import xattr
2
3# Path to a file you want to manipulate
4path = 'test.txt'
5
6# Create a dummy file for the example
7with open(path, 'w') as f:
8    f.write('Hello world')
9
10# Set an extended attribute
11# Note: On Linux, namespaces like 'user.' are usually required
12xattr.setxattr(path, 'user.comment', b'This is a test comment')
13
14# Get an extended attribute
15value = xattr.getxattr(path, 'user.comment')
16print(f"Attribute value: {value.decode('utf-8')}")
17
18# List all extended attributes
19attribs = xattr.listxattr(path)
20print(f"All attributes: {attribs}")
21
22# Remove an extended attribute
23xattr.removexattr(path, 'user.comment')
xattr_file_extended_attributes_set_get_list_remove.py - Raysurfer Public Snippets