Python add custom property/metadata to file

后端 未结 2 1244
日久生厌
日久生厌 2020-12-16 06:14

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 var

2条回答
  •  半阙折子戏
    2020-12-16 06:51

    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.

提交回复
热议问题