Python将自定义属性/元数据添加到文件 [英] Python add custom property/metadata to file

查看:349
本文介绍了Python将自定义属性/元数据添加到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,是否可以将自定义属性/元数据添加到文件中? 例如,我需要添加"FileInfo"作为文件的新属性. 我需要一种适用于各种文件格式的方法

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

推荐答案

注意:此答案仅适用于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.

在Python中,这是由os模块通过来实现的setxattr() getxattr() 函数

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'

请注意,您必须在xattr值前面加上"user.",否则可能会引起OSError.

Note that you must prepend the xattr value with "user." otherwise this may raise an OSError.

这篇关于Python将自定义属性/元数据添加到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆