Skip to content

Instantly share code, notes, and snippets.

@webstory
Created December 20, 2018 05:14
Show Gist options
  • Save webstory/569dab479c38534c46aa2ec2508836dd to your computer and use it in GitHub Desktop.
Save webstory/569dab479c38534c46aa2ec2508836dd to your computer and use it in GitHub Desktop.
Google Cloud Storage getDirectories for python
import googleapiclient.discovery
def list_directories(bucket, prefix):
"""Returns a list of directory of the objects within the given bucket."""
service = googleapiclient.discovery.build('storage', 'v1')
# Create a request to objects.list to retrieve a list of objects.
req = service.objects().list(
bucket=bucket,
prefix=prefix,
delimiter='/'
)
all_objects = []
# If you have too many items to list in one request, list_next() will
# automatically handle paging with the pageToken.
while req:
resp = req.execute()
all_objects.extend(resp.get('prefixes', []))
req = service.objects().list_next(req, resp)
return all_objects
if __name__ == '__main__':
dirs = list_directories(
'someBucket',
'some/dir/' # Must don't forget trailing slash
)
for directory in dirs:
print(directory)