Skip to main content
The Opus SDK lets you work with files from inside an Opus Code task—download files from Opus storage, create new files, upload files back to storage, and more. Aside from the Opus SDK, you can use a wide range of Python packages; the full list is available in Available Packages.

Setup

Inside an Opus Code task, Opus is already defined and ready to use.

File Operations

All file operations are accessed via Opus.file.

Downloading a File

Use Opus.file.download(file_url) to fetch a file from Opus storage by its URL:
file = Opus.file.download("https://files.opus.com/path/to/file.pdf")
This returns an OpusFile object.
Modifications to downloaded files are local only unless uploaded via Opus.file.upload, which creates a new file and returns a new URL; the original remote file is never modified.

Getting a Presigned Download URL

Use Opus.file.presigned_download(file_url, expiry=None) to get a presigned URL for downloading a file without fetching it locally:
url = Opus.file.presigned_download("https://files.opus.com/path/to/file.pdf")
You can optionally set a custom expiry (in seconds, between 60 and 86400):
url = Opus.file.presigned_download("https://files.opus.com/path/to/file.pdf", expiry=3600)  # 1 hour
If no expiry is provided, the server default is used.
The expiry must be between 60 seconds (1 minute) and 86400 seconds (24 hours). Values outside this range raise InvalidFileExpiryError.

Creating a File

Use Opus.file.create(file_name, file_type) to create a new empty file:
new_file = Opus.file.create("my_report", "PDF")
The first argument is the file name (without extension), the second is the file type. The extension is added automatically based on the type. This returns an OpusFile object.
If the file isn’t uploaded via Opus.file.upload, the created file won’t be persisted.
Creating a file with a name that already exists in the current session raises FileAlreadyExistsError.

Supported File Types

Pass any of these as the file_type argument:
TypeExtensionContent Type
JPEG.jpegimage/jpeg
PNG.pngimage/png
JPG.jpgimage/jpg
CSV.csvtext/csv
PDF.pdfapplication/pdf
DOCX.docxapplication/vnd.openxmlformats...
PPTX.pptxapplication/vnd.openxmlformats...
XLS.xlsapplication/vnd.ms-excel
XLSX.xlsxapplication/vnd.openxmlformats...
TXT.txttext/plain
MD.mdtext/markdown
JSON.jsonapplication/json
HTML.htmltext/html
XML.xmlapplication/xml
The type is case-insensitive: "pdf", "PDF", and "Pdf" all work.

Uploading a File

Use Opus.file.upload(file, access_scope="all") to upload an OpusFile to Opus storage.
file_url = Opus.file.upload(new_file)
print(file_url)  # "https://files.opus.com/..."
The access_scope parameter is optional and defaults to "all".
Code Playground: In the code playground, the access_scope is always "unlisted" regardless of the value provided.
You can upload the same file multiple times. Each upload returns a new URL.

Supported Access Scopes

ScopeDescription
allVisible to everyone (default)
workspaceVisible only to current workspace members
unlistedNot listed — accessible only via direct file URL
The scope is case-insensitive: "Workspace", "WORKSPACE", and "WorkSpace" all work.
file_url = Opus.file.upload(new_file, access_scope="workspace")

OpusFile Interface

OpusFile is the object returned by download() and create(). Its attributes are read-only.

Properties

PropertyTypeDescription
file_namestr | NoneFile name without extension.
file_extstrExtension including leading dot (e.g. ".pdf").
file_typestrResolved file type enum value. Check Supported File Types.
file_sizeintCurrent size on disk in bytes.
file = Opus.file.create("report", "PDF")
print(file.file_name)  # "report"
print(file.file_ext)  # ".pdf"
print(file.file_type)  # FileType.PDF
print(file.file_size)  # 0 (empty file)

Operations

MethodDescription
read_bytes() -> bytesRead entire file content as bytes.
read_text(encoding="utf-8") -> strRead entire file content as a string.
write_bytes(data: bytes)Replace file content with binary data.
write_text(data: str, encoding="utf-8")Replace file content with text.
open(mode="rb")Open the underlying file and return a file handle.

Examples

Reading:
# As text
text = file.read_text()

# As bytes
data = file.read_bytes()

# Using a file handle
with file.open("r") as f:
  for line in f:
    print(line)
Writing:
# Replace all content
file.write_text("Hello, world!")
file.write_bytes(b"\x50\x4b\x03\x04...")

# Streaming writes
with file.open("w") as f:
  f.write("line 1\n")
  f.write("line 2\n")

# Appending
with file.open("a") as f:
  f.write("appended line\n")
Download, modify, and re-upload:
file = Opus.file.download("https://files.opus.com/reports/data.csv")
original = file.read_text()
modified = original.replace("old_value", "new_value")
file.write_text(modified)
new_url = Opus.file.upload(file)
Create a CSV from scratch:
import csv

output = Opus.file.create("results", "CSV")

with output.open("w") as f:
  writer = csv.writer(f)
  writer.writerow(["name", "score"])
  writer.writerow(["Alice", 95])
  writer.writerow(["Bob", 87])

file_url = Opus.file.upload(output)
Create a JSON file:
import json

output = Opus.file.create("config", "JSON")
output.write_text(json.dumps({"key": "value", "count": 42}, indent=2))

file_url = Opus.file.upload(output)
Process a downloaded file line by line:
file = Opus.file.download("https://files.opus.com/logs/app.txt")

with file.open("r") as f:
  for line in f:
    if "ERROR" in line:
      print(line.strip())

Working with File Formats

For format-specific helpers and patterns, check the dedicated guide: Working with File Formats.

Errors

All SDK exceptions inherit from OpusError and are available via Opus.errors:
try:
  file = Opus.file.download("https://files.opus.com/missing.pdf")
except Opus.errors.FileAPIError as e:
  print(f"Download failed: {e}")
  print(f"Status code: {e.status_code}")
  print(f"Response: {e.response_body}")
try:
  Opus.file.create("report", "MP4")
except Opus.errors.UnsupportedFileTypeError as e:
  print(f"Bad type: {e}")
try:
  Opus.file.create("report", "PDF")
  Opus.file.create("report", "PDF")  # same name again
except Opus.errors.FileAlreadyExistsError as e:
  print(f"Duplicate: {e}")
ExceptionWhen it’s raised
OpusErrorBase class for all SDK errors. Also raised directly for generic failures.
FileAPIErrorAn API call failed (download or upload).
FileAlreadyExistsErrorcreate() with a name that already exists.
UnsupportedFileTypeErrorcreate() with an unrecognized file type.
InvalidFileExpiryErrorpresigned_download() with an expiry outside the range.
UnsupportedAccessScopeErrorupload() with an invalid access scope.
PathTraversalErrorFile name attempted to escape the allowed directory.

Available Packages

Browse the full list of Python packages you can import in Opus Code.

Working with File Formats

Format-specific helpers for reading and writing PDFs, spreadsheets, and more.

Opus Code

Write custom Python code directly in your workflow.