How to list and delete Google Cloud Storage files from Google App Engine

In this article I’ll show you how can list and delete files of google cloud storage from google app engine.

Google App Engine has an API that let you access Google Cloud Storage. If you need more info about this API you can read the whole documentation on Google Developers:


https://developers.google.com/appengine/docs/python/googlestorage/functions?hl=en

How to list cloud storage files from app engine:

from google.appengine.api import files

bucket = '/gs/my-bucket'
print files.gs.listdir(bucket)

How to delete cloud storage files from app engine:

form google.appengine.api import files

# Delete one Google Cloud Storage file
file = '/gs/my-bucket/my-file.txt'
files.delete(file)

# Delete a list of files using listdir()
files.delete(*files.gs.listdir('/gs/my-bucket'))

In this case when you try to delete all the bucket files there’s a limit of 1000 files when you use listdir().

One simple way to delete more than 1000 files on bucket is use While loop.

How to delete more than 1000 files on Google Cloud Storage bucket from Google App Engine:

form google.appengine.api import files

bucket = '/gs/my-bucket'
# Delete all the files (more than 1000 files) on bucket.
ficheros = files.gs.listdir(bucket)
while ficheros:
  files.delete(*ficheros)
  ficheros = files.gs.listdir(bucket)

Leave a comment

Create a website or blog at WordPress.com

Up ↑