CSV to Datatable

Hello,
I am trying to import a csv-file from the desktop with the fileupload-component. This works only to the point when I try to write the csv-File to a table. Then I get:

“AttributeError: module ‘anvil’ has no attribute ‘media’”
Used the code drom the docs in a sverver-module:

import anvil.server
@anvil.server.callable
def store_data(file):
with anvil.media.TempFile(file) as file_name:
if file.content_type == ‘text/csv’:
df = pd.read_csv(file_name)
else:
df = pd.read_excel(file_name)
for d in df.to_dict(orient=“records”):
# d is now a dict of {columnname → value} for this row
# We use Python’s **kwargs syntax to pass the whole dict as
# keyword arguments
app_tables.table_1.add_row(**d)

Any solution?
Kind Regards
Andreas

I think you need to do :

import anvil.media

It’s hidden away in the docs a bit, but it does say (my bold) :

You can trigger a Media object download in the user’s browser by calling anvil.media.download(my_media_object) in any client-side code. (Remember to import anvil.media first!)

Also, please wrap code in your posts with triple backticks (```) so it displays like this :

import anvil.server
@anvil.server.callable
def store_data(file):
  with anvil.media.TempFile(file) as file_name:
    if file.content_type == ‘text/csv’:
      df = pd.read_csv(file_name)
    else:
      df = pd.read_excel(file_name)
  
    for d in df.to_dict(orient=“records”):
      # d is now a dict of {columnname → value} for this row
      # We use Python’s **kwargs syntax to pass the whole dict as
      # keyword arguments
      app_tables.table_1.add_row(**d)
3 Likes

If you don’t want to do the csv-to-table code yourself, or just want a peak at some code that works I created a cloneable example app for this exact topic here: However It does not use pandas.

But if what you are trying to do is have the server process the file then follow @david.wylie 's example.
There are also a ton of forum posts about loading a file into a file loader as a media object and then using that on the server by turning the result of .get_bytes() from a media object back into a file or a file stream (file like object in memory).

pandas seems like overkill just for reading CSV files. If I remember correctly, pandas delegates that job to one of its dependencies, like numpy. See Reading and writing files — NumPy v1.23 Manual

So why load up an entire a battleship when all you need (for the job) is a speedboat?