如何在 Python 中保存 OneNote 附件文件

如何在 Python 中保存 OneNote 附件文件

OneNote .one 文件可以包含嵌入的文件附件:任何通过 OneNote 中的 Insert → File Attachment 插入到页面的文件类型。Aspose.Note FOSS for Python 通过 AttachedFile 类公开这些附件,该类提供原始文件名和嵌入文件的原始字节。


先决条件

pip install aspose-note

步骤 1: 加载文档

from aspose.note import Document

doc = Document("MyNotes.one")

步骤 2:查找所有已附加的文件

使用 GetChildNodes(AttachedFile) 递归收集文档中的每个附件,无论它出现在页面还是大纲的哪个位置:

from aspose.note import Document, AttachedFile

doc = Document("MyNotes.one")
attachments = doc.GetChildNodes(AttachedFile)
print(f"Found {len(attachments)} attachment(s)")

步骤 3:将每个附件保存到磁盘

访问 af.Bytes 获取原始文件内容,使用 af.FileName 获取原始名称。始终防范 None 文件名:当文件中未存储文件名元数据时,库会返回 None

from aspose.note import Document, AttachedFile

doc = Document("MyNotes.one")

for i, af in enumerate(doc.GetChildNodes(AttachedFile), start=1):
    name = af.FileName or f"attachment_{i}.bin"
    with open(name, "wb") as f:
        f.write(af.Bytes)
    print(f"Saved: {name} ({len(af.Bytes):,} bytes)")

完整示例

此脚本从 .one 文件中提取所有附件,并将它们保存到专用的输出目录:

from pathlib import Path
from aspose.note import Document, AttachedFile

def save_all_attachments(one_path: str, out_dir: str = "attachments") -> None:
    doc = Document(one_path)
    out = Path(out_dir)
    out.mkdir(exist_ok=True)

    attachments = doc.GetChildNodes(AttachedFile)
    if not attachments:
        print("No attachments found.")
        return

    for i, af in enumerate(attachments, start=1):
        name = af.FileName or f"attachment_{i}.bin"
        dest = out / name
        dest.write_bytes(af.Bytes)
        print(f"  [{i}] {name}  ({len(af.Bytes):,} bytes)")

    print(f"\nSaved {len(attachments)} file(s) to '{out_dir}/'")

save_all_attachments("MyNotes.one")

备注

  • af.Bytes 在无法从二进制文件解析附件数据时返回 b""(空字节)。如果想跳过空附件,请在保存前检查 len(af.Bytes) > 0
  • 如果附件上应用了任何 OneNote 标签,af.Tags 将是 NoteTag 对象的列表。
  • Aspose.Note FOSS for Python 可以读取 .one 文件,但不写回 .one。无法创建或修改附件。

另请参阅

 中文