Python add custom property/metadata to file

2019-04-11 09:48发布

问题:

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:

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.