Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python add custom property/metadata to file

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

like image 996
CherryBelle Avatar asked Dec 16 '16 11:12

CherryBelle


People also ask

How do I add metadata to a file in python?

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.

How do I add custom metadata to a file?

Click the file to which you want to add metadata. In the file's preview screen, click the metadata icon in the right-hand side-bar. Next to Metadata, click Add, then choose the metadata template you'd like to use.


1 Answers

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.

like image 115
Delgan Avatar answered Nov 23 '22 21:11

Delgan