How to save an updated csv to Google Drive?

I’ve successfully connected to Google Drive and imported a csv into the anvil environment, however I’m wondering now how I can save a csv to that same Google Drive.

I create the dataframe using pandas, but I’m not entirely sure how to save it.

That’s a first step, but really I want to modify an existing csv file currently on the drive.

So the steps would be:

  1. Pull csv from Google Drive. (Successfully Completed)

  2. Create new dataframe and append it to original csv (Successfully Completed)

  3. Replace original csv in Google Drive folder with updated csv (Not Yet Completed).

Would appreciate some help, thanks!

I had this issue before:

Changing the content of a google drive file

to change the contents do

my_file = app_files.my_file
csv_file = pandas_csv_file

# set bytes needs a string object... 
my_file.set_bytes(csv_file.get_bytes().decode())

You may also have to do

csv_file = anvil.BlobMedia('text/csv', pandas_csv_file)
my_file.set_bytes(csv_file.get_bytes().decode())

Though note - when I did this I could no longer open the csv in google sheets for some reason - only in docs. It did download as a CSV as expected…

You can check this has worked by going to the file in your google drive, right clicking → manage versions.

edit: corrections

Should this be:

my_file = app_files.my_file
csv_file = anvil.BlobMedia('text/csv', pandas_csv_file)
my_file.set_bytes(csv_file.get_bytes().decode())

My confusion is that in your answer you have:
my_file.set_bytes(csv.get_bytes().decode())

… but this doesn’t show how you use “csv_file” since you are decoding “csv”

Actually just let me show you the blocks of code:

Here I call in the file:

  folder = app_files.my_folder

  for f in folder.list_files():
    with anvil.media.TempFile(f) as file_name:
      if f['title'] == 'my_file.csv':
        my_file=f
        tobemanipulated = pd.read_csv(file_name)

Then I do some stuff and create a new dataframe and append it to the old one:

  df=pd.DataFrame()
  df['Name']=name

  tobemanipulated = tobemanipulated.append(df)

  csv_file = anvil.BlobMedia('text/csv', tobemanipulated)
  my_file.set_bytes(csv_file.get_bytes().decode())

This throws an error saying that a dataframe has no property called ‘decode’

Corrected the code above - my mistake. You’re right it should have been csv_file

So I think you need to convert your df to csv using the pandas DataFrame method to_csv()
something like…

csv_file = anvil.BlobMedia('text/csv', tobemanipulated.to_csv())
2 Likes

Seems like this worked! Thanks so much!

1 Like