Live Chat

We'll need to share your messages (and your email address if you're logged in) with our live chat provider, Drift. Here's their privacy policy.

If you don't want to do this, you can email us instead at contact@anvil.works.

Files on Disk

You can write to and from files in Server Modules using Media objects.

You can also write to and from files using Python’s open.

Media Object to temporary file

To write to a temporary file, use anvil.media.TempFile(media_object) in a with block.

If you’re using a Python library that wants you to pass it a filename, this can be really useful for writing some data into a file, then passing the file_name to the library you’re using.

import anvil.media

@anvil.server.callable
def write_media_to_file(media_object):
  with anvil.media.TempFile(media_object) as file_name:
    # Now there is a file in the filesystem containing the contents of media_object.
    # The file_name variable is a string of its full path.

The file is written to the filesystem as soon as the with block begins. The file will be deleted when the with block exits.

Media Object from file

To read from an existing file, use anvil.media.from_file(file_name, [content_type], [name]).

import anvil.media

@anvil.server.callable
def read_from_file(file_name):
  media_object = anvil.media.from_file(file_name, [content_type], [name])
  return media_object

This creates a Media object with the contents of the file.

Read and write files as normal

You can also use Python’s open to read and write files as normal. Your filesystem is your own; other users do not have access to it.

def write_a_file(my_string):
  with open('/tmp/my-file.txt', 'w+') as f:
    f.write(my_string)