作者:youyiyang | 来源:互联网 | 2022-12-09 17:17
通过添加标志,使用gsutil将大量文件并行下载到本地计算机上是微不足道的。-m
gsutil -m cp gs://my-bucket/blob_prefix* .
在python中,我一次只能下载一个文件:
client = storage.Client()
bucket = client.get_bucket(gs_bucket_name)
blobs = [blob for blob in bucket.list_blobs(prefix=blob_prefix)]
for blob in blobs:
blob.download_to_filename(filename)
最好是我想直接将数据下载到内存中(类似于blob.download_as_string()
),最好是下载到生成器中。顺序并不重要。
这项功能是否存在于python API中?
如果没有,什么是最好的方法?
编辑
我已经实现了这一技巧:
def fetch_data_from_storage(fetch_pattern):
"""Download blobs to local first, then load them into Generator."""
tmp_save_dir = os.path.join("/tmp", "tmp_gs_download")
if os.path.isdir(tmp_save_dir):
shutil.rmtree(tmp_save_dir) # empty tmp dir first
os.makedirs(tmp_save_dir) # create tmp dir
download_command = ["gsutil", "-m", "cp", "gs://{}/{}".format(bucket.name, fetch_pattern), tmp_save_dir]
resp = subprocess.call(download_command)
for file in os.listdir(tmp_save_dir):
with open(os.path.join(tmp_save_dir, file), 'r') as f_data:
cOntent= json.load(f_data)
yield content
请告知这是否在某个地方以更好的方式实现。