You can write to and from files in Server Modules using Media objects.
You can also write to and from files using Python’s
To write to a temporary file, use
anvil.media.TempFile(media_object) in a
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.
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.
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)