10

In Python, is it possible to add custom property/metadata to a file? For example, I need to add "FileInfo" as a new property of the file. I need a method that works on various file formats

1
  • 4
    When you say "to a file", are you referring to the Python file object or to the file itself ? Commented Dec 16, 2016 at 12:24

1 Answer 1

13

Heads up: this answer only works on Linux

You can make use of extended file attributes which is a filesystem feature that do just what you want: store custom metadata along files.

In Python, this is implemented by the os module through setxattr() and getxattr() functions.

import os

os.setxattr('foo.txt', 'user.bar', b'baz')
os.getxattr('foo.txt', 'user.bar')  # => b'baz'

Note that you must prepend the xattr value with "user." otherwise this may raise an OSError.

Sign up to request clarification or add additional context in comments.

3 Comments

Note that the attribute is not copied if the file is copied to a new place. But moving will keep the attribute, even moving between volumes.
Sucks it doesn't stay when copying files.
@LewisMorris You should use shutil.copy2() or cp -a which will try to preserve extended attributes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.