提问人:Primoz 提问时间:11/16/2023 最后编辑:tripleeePrimoz 更新时间:11/16/2023 访问量:33
使用 DirectoryLoader 将文件创建和修改日期添加到元数据中
Add file creation and modification date to metadata with DirectoryLoader
问:
我正在使用 LangChain 库,并且对是否可以使用 DirectoryLoader 加载文件创建和/或修改日期以及文件内容并将该信息添加到文档的元数据中感兴趣。可能吗?怎么做呢?
目前,我只加载 docx 文件,但我也想在将来加载其他文档。我目前的代码片段是:
loader = DirectoryLoader(dir, glob="**/*.docx", show_progress=True, silent_errors=True)
docs = loader.load()
答:
0赞
Primoz
11/16/2023
#1
经过一番研究,我发现了以下但不是最佳解决方案。我重新实现了 ,为新加载的文档添加日期元数据。DateDirectoryLoader
load_file
class DateDirectoryLoader(DirectoryLoader):
def load_file(
self, item: Path, path: Path, docs: List[Document], pbar: Optional[Any]
) -> None:
prev_len = len(docs)
super().load_file(item, path, docs, pbar)
if len(docs) > prev_len:
# if any file was loaded by super().load_file == no error loading
stat = os.stat(str(item))
creation_date = datetime.fromtimestamp(stat.st_ctime).isoformat()
modification_date = datetime.fromtimestamp(stat.st_mtime).isoformat()
for doc in docs[prev_len:]:
doc.metadata['creation_date'] = creation_date
doc.metadata['modification_date'] = modification_date
重要提示:仅在 Windows 中是创建日期,在 Unix 上是元数据修改名称。在此处查找适用于多个操作系统的解决方案:如何获取文件创建和修改日期/时间?stat.st_ctime
评论