跳到主要内容

Zotero 文献库

收藏0

用 pyzotero 程序化管理 Zotero 文献库:检索条目、新建与更新条目、整理分类与标签、导出引用格式、上传 PDF 附件,支持 Web API 与本地 API。

让 AI 安装

星光尘缘LV2最新版本 0.1.0更新于 2026-11-24下载 0 次

references/files-attachments.md

4.3 KB查看排版效果
1# Files & Attachments
2
3## Downloading Files
4
5```python
6# Get raw binary content of an attachment
7raw = zot.file('ATTACHMENTKEY')
8with open('paper.pdf', 'wb') as f:
9 f.write(raw)
10
11# Convenient wrapper: dump file to disk
12# Uses stored filename, saves to current directory
13zot.dump('ATTACHMENTKEY')
14
15# Dump to a specific path and filename
16zot.dump('ATTACHMENTKEY', 'renamed_paper.pdf', 'papers')
17# Create the directory first. Returns None on success, not a path.
18```
19
20`dump()` uses the provided filename or stored attachment filename. For responses classified as HTML snapshots, 1.15.2 appends `.zip` to that name; ZIP/EPUB handling can return an archive member. Verify the saved bytes and type instead of assuming every snapshot is a ZIP or is named with its key. Remote `/file` downloads require stored, synced files and appropriate permissions; linked files are not uploaded to Zotero storage.
21
22## Finding Attachments
23
24```python
25# Get child items (attachments, notes) of a parent item
26children = zot.children('PARENTKEY')
27attachments = [c for c in children if c['data']['itemType'] == 'attachment']
28
29# Get the attachment key
30for att in attachments:
31 key = att['data']['key']
32 filename = att['data'].get('filename') # absent on linked URLs
33 content_type = att['data']['contentType']
34 link_mode = att['data']['linkMode'] # 'imported_file', 'linked_file', 'imported_url', 'linked_url'
35```
36
37## Uploading Attachments
38
39**Note**: Upstream still labels attachment helpers beta. The simple/both helpers below require the remote API; local uploads need a manually built attachment dict and Zotero 10+ authorization (see [authentication.md](authentication.md)).
40
41```python
42# Simple upload: one or more files by path
43result = zot.attachment_simple(['/path/to/paper.pdf', '/path/to/notes.docx'])
44
45# Upload as child items of a parent
46result = zot.attachment_simple(['/path/to/paper.pdf'], parentid='PARENTKEY')
47
48# Upload with custom filenames: list of (name, path) tuples
49result = zot.attachment_both([
50 ('Paper 2024.pdf', '/path/to/paper.pdf'),
51 ('Supplementary.pdf', '/path/to/supp.pdf'),
52], parentid='PARENTKEY')
53
54# Upload files to existing attachment items
55result = zot.upload_attachments(attachment_items, basedir='/path/to/files/')
56# Existing entries need editable attachment dicts with key + version;
57# filename resolves on disk relative to basedir. Do not set parentid for existing items.
58if result['failure']:
59 raise RuntimeError(result['failure'])
60```
61
62Upload result structure:
63```python
64{
65 'success': [attachment_item1, ...],
66 'failure': [attachment_item2, ...],
67 'unchanged': [attachment_item3, ...]
68}
69```
70
71## Attachment Templates
72
73```python
74# Get template for a file attachment
75template = zot.item_template('attachment', linkmode='imported_file')
76# linkmode options: 'imported_file', 'linked_file', 'imported_url', 'linked_url'
77
78# Available link modes
79modes = zot.item_attachment_link_modes()
80```
81
82## Downloading All PDFs from a Collection
83
84```python
85import os
86
87collection_key = 'COLKEY'
88output_dir = '/path/to/output/'
89os.makedirs(output_dir, exist_ok=True)
90
91items = zot.everything(zot.collection_items_top(collection_key))
92for item in items:
93 # A top-level item can itself be a standalone attachment.
94 children = ([item] if item['data']['itemType'] == 'attachment' else
95 zot.everything(zot.children(item['data']['key'])))
96 for child in children:
97 if child['data']['itemType'] == 'attachment' and \
98 child['data'].get('contentType') == 'application/pdf' and \
99 child['data'].get('linkMode') in {'imported_file', 'imported_url'}:
100 try:
101 # Key-based filenames prevent collisions between identically named PDFs.
102 zot.dump(child['key'], filename=f"{child['key']}.pdf", path=output_dir)
103 except Exception as e:
104 print(f"Failed to download {child['data']['key']}: {e}")
105```
106
107Upload results are distinct from `create_items()` results: lists under `success`, `failure`, and `unchanged`. Returned successful entries carry the current `version`; creation failures may include an `error` dict. The SDK manages file authorization, upload, and registration through `/items/{key}/file`, including MD5 preconditions and the storage URL returned by Zotero. A completed metadata create alone does not prove the file uploaded. See [official upload protocol](https://www.zotero.org/support/dev/web_api/v3/file_upload).

文件内容是平台检查时读出的文本,只供查看。平台不会运行包里的任何脚本或程序。