Can I write to a Media object as a file?

Good question. The best way to do this is to use an intermediate BytesIO objects to buffer the data. Something like this:

import anvil
from io import BytesIO

def write_media():
  data = BytesIO()

  # ... do something that writes to 'data' as a file here ...
  # For example:
  data.write("foo")

  # Now reset the stream so you can read from it:
  data.seek(0)

  return anvil.BlobMedia("text/plain", data.read(), name="my_file.txt")

Hope that helps!