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.