Python add custom property/metadata to file

2019-04-11 10:00发布

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条回答
霸刀☆藐视天下
2楼-- · 2019-04-11 10:09

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.

查看更多
登录 后发表回答