Python add custom property/metadata to file

血红的双手。 提交于 2019-12-30 03:29:06

问题


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:


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.

Unfortunately, this feature is only available on Linux systems.




回答2:


The easy way to do this is to simply add your new attribute to the file object instance. Eg,

with open('qdata') as f:
    f.fileinfo = {'description': 'this file contains stuff...'}
    print(f.fileinfo)

output

{'description': 'this file contains stuff...'}

Alternatively, create your own file object by deriving from one of the classes defined in the io module.



来源:https://stackoverflow.com/questions/41183819/python-add-custom-property-metadata-to-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!