Python实现删除Google Cloud Storage含指定字符串的文件
解决方案:Google Cloud Storage 批量删除指定特征文件
一、删除包含_lc_的文件
遍历存储桶内所有文件(Blob),通过检查文件名是否包含目标字符串_lc_筛选待删除文件,再调用blob.delete()执行删除。
示例代码:
from google.cloud import storage def delete_files_with_lc(bucket_name): # 初始化GCS客户端 storage_client = storage.Client() bucket = storage_client.bucket(bucket_name) # 遍历存储桶内所有Blob for blob in bucket.list_blobs(): # 检查文件名是否包含"_lc_" if '_lc_' in blob.name: # 执行删除(可先打印文件名验证,确认后再删除) print(f"Deleting file: {blob.name}") # blob.delete() # 替换为你的存储桶名称 delete_files_with_lc("your-bucket-name")
提示:测试时可先注释
blob.delete(),打印待删除文件名确认筛选结果无误后,再取消注释执行实际删除。
二、删除today早于特定日期的文件
从文件名中提取today字段(示例假设格式为YYYYMMDD),转换为日期对象后与指定日期比较,筛选出早于目标日期的文件进行删除。
示例代码:
from google.cloud import storage from datetime import datetime def delete_files_before_date(bucket_name, target_date_str): # 转换目标日期为datetime对象(需与文件名中的日期格式一致) target_date = datetime.strptime(target_date_str, "%Y%m%d").date() storage_client = storage.Client() bucket = storage_client.bucket(bucket_name) for blob in bucket.list_blobs(): # 拆分文件名提取today部分:按下划线分割,倒数第二个元素为today(去掉.tif后缀) filename_parts = blob.name.split('_') if len(filename_parts) < 2: continue # 跳过不符合命名格式的文件 today_str = filename_parts[-1].replace('.tif', '') try: today_date = datetime.strptime(today_str, "%Y%m%d").date() # 判断是否早于目标日期 if today_date < target_date: print(f"Deleting file (date too old): {blob.name}") # blob.delete() except ValueError: # 跳过日期格式不正确的文件 continue # 替换为你的存储桶名称和目标日期(格式YYYYMMDD) delete_files_before_date("your-bucket-name", "20240101")
三、组合条件删除
如果需要同时满足「包含_lc_且today早于指定日期」,可合并筛选逻辑:
from google.cloud import storage from datetime import datetime def delete_files_with_lc_and_before_date(bucket_name, target_date_str): target_date = datetime.strptime(target_date_str, "%Y%m%d").date() storage_client = storage.Client() bucket = storage_client.bucket(bucket_name) for blob in bucket.list_blobs(): if '_lc_' not in blob.name: continue filename_parts = blob.name.split('_') if len(filename_parts) < 2: continue today_str = filename_parts[-1].replace('.tif', '') try: today_date = datetime.strptime(today_str, "%Y%m%d").date() if today_date < target_date: print(f"Deleting file: {blob.name}") # blob.delete() except ValueError: continue delete_files_with_lc_and_before_date("your-bucket-name", "20240101")
注意事项
- 确保已安装
google-cloud-storage库:pip install google-cloud-storage - 已配置GCS认证(本地开发可使用
gcloud auth application-default login,服务器环境可使用服务账号密钥)
内容的提问来源于stack exchange,提问作者M. Merida-Floriano
相关产品推荐
相关产品推荐

