Reputation: 2797
I need to move some files in Google's Cloud Storage from one folder to another folder via Python. Looking through their docs, I can't seem to find anything to move the actual file, I would need to copy the file to the other directory, then delete the original file.
I was able to find copy_blob, however, I'm not able to see anything in there to be able to specify the folder. Is there a way to specify the folder in which I want to copy the file too? Or is there another way I can move the file from one folder to another?
Upvotes: 4
Views: 9133
Reputation: 21520
Google Cloud Storage doesn't have a true sense of "folders". If you're just "moving" the files in the same bucket, what you're actually doing is just changing the name that maps to the blob in storage, and you can use rename_blob
for that. For example:
>>> from google.cloud import storage
>>> storage_client = storage.Client()
>>> bucket = storage_client.get_bucket('YOUR_BUCKET_NAME')
>>> blob = bucket.get_blob('/path/to/folder/foo.txt')
>>> blob.name
'/path/to/folder/foo.txt'
>>> bucket.rename_blob(blob, '/new/location/foo.txt')
>>> list(bucket.list_blobs())
[<Blob: YOUR_BUCKET_NAME, b'/new/location/foo.txt'>]
If you're "moving" the file between buckets, you'll need to use copy_blob
, because you'll actually need to be transferring data between buckets. When using this function, the name
parameter will be the full path to the file, including any "folders".
Upvotes: 8