Created
December 20, 2018 05:14
-
-
Save webstory/569dab479c38534c46aa2ec2508836dd to your computer and use it in GitHub Desktop.
Google Cloud Storage getDirectories for python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
References: