How to Save Attached Files from OneNote in Python
OneNote .one files can contain embedded file attachments: any file type that was inserted into a page using Insert → File Attachment in OneNote. Aspose.Note FOSS for Python exposes these through the AttachedFile class, which provides the original file name and the raw bytes of the embedded file.
Prerequisites
pip install aspose-noteStep 1: Load the Document
from aspose.note import Document
doc = Document("MyNotes.one")Step 2: Find All Attached Files
Use GetChildNodes(AttachedFile) to recursively collect every attachment in the document, regardless of which page or outline it appears on:
from aspose.note import Document, AttachedFile
doc = Document("MyNotes.one")
attachments = doc.GetChildNodes(AttachedFile)
print(f"Found {len(attachments)} attachment(s)")Step 3: Save Each Attachment to Disk
Access af.Bytes for the raw file content and af.FileName for the original name. Always guard against a None filename: the library returns None when the filename metadata was not stored in the file:
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)")Complete Example
This script extracts all attachments from a .one file and saves them to a dedicated output directory:
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")Notes
af.Bytesreturnsb""(empty bytes) when the attachment data could not be parsed from the binary file. Checklen(af.Bytes) > 0before saving if you want to skip empty attachments.af.Tagsis a list ofNoteTagobjects if the attachment has any OneNote tags applied to it.- Aspose.Note FOSS for Python reads
.onefiles but does not write back to.one. You cannot create or modify attachments.