Read the contents of a text file in Google drive

I have set up google drive folder and can access audio and image files on it. Although I can also open a simple .txt file and confirm that its content type is text/plain, but I cannot read the contents of into a string at the server side.

Code Sample:

   text_file = folder.get(file_name + '.txt')
      if text_file != None:
        if text_file.content_type == 'text/plain':
          text = str(text_file.read())

Please can you advise?

Clone link:
share a copy of your app

Hi @alastaircozens.

The reason that code isn’t working is because the read() method doesn’t work on Google Drive files in Anvil.

When you open a file in Python, you get a file-like object on which you can use methods such as read() and write(). However, when you open a Google Drive file in Anvil, you get an anvil.google.drive.File object, whose methods are get_bytes(), set_bytes() and set_media() instead.

What you want to use in this specific example is get_bytes(), and not read(). I’d recommend taking a closer look at our Google Drive integration documentation for more information.

Hope this helps!

1 Like

Thank you Patricia

I followed your advice and initially found that get_bytes() yielded file contents which could not be returned to the client without generating a serialization error. However, this can be remedied by string conversion:

    folder = app_files.drive.get(folder_name)
    text_file = folder.get(file_name)
    file_contents = str(text_file.get_bytes(), 'utf-8')
2 Likes