[英]How to get ONLY bottom level sub-folders from amazon S3 with aioboto3 fast and asynchronously
[英]How can I get ONLY files from S3 with python aioboto3 or boto3?
我有這個代碼,我只想要以文件結尾的路徑,而沒有中間的空文件夾。 例如:
data/folder1/folder2
data/folder1/folder3/folder4/file1.txt
data/folder5/file2.txt
從這些路徑我只想要:
data/folder1/folder3/folder4/file1.txt
data/folder5/file2.txt
我正在使用此代碼,但它也為我提供了以目錄結尾的路徑:
subfolders = set()
current_path = None
result = await self.s3_client.list_objects(Bucket=bucket, Prefix=prefix)
objects = result.get("Contents")
try:
for obj in objects:
current_path = os.path.dirname(obj["Key"])
if current_path not in subfolders:
subfolders.add(current_path)
except Exception as exc:
print(f"Getting objects with prefix: {prefix} failed")
raise exc
你不能檢查是否有擴展? 順便說一句,您不需要檢查集合中路徑的存在,因為集合將始終保留唯一項目。
list_objects
不返回任何指示項是文件夾還是文件。 所以,這看起來很實用。
請檢查: https : //boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.list_objects
subfolders = set()
current_path = None
result = await self.s3_client.list_objects(Bucket=bucket, Prefix=prefix)
objects = result.get("Contents")
try:
for obj in objects:
current_path = os.path.dirname(obj["Key"])
if "." in current_path:
subfolders.add(current_path)
except Exception as exc:
print(f"Getting objects with prefix: {prefix} failed")
raise exc
我建議在這里使用 boto3 Bucket資源,因為它簡化了分頁。
以下是如何獲取 S3 存儲桶中所有文件列表的示例:
import boto3
bucket = boto3.resource("s3").Bucket("mybucket")
objects = bucket.objects.all()
files = [obj.key for obj in objects if not obj.key.endswith("/")]
print("Files:", files)
值得注意的是,獲取 S3 存儲桶中所有文件夾和子文件夾的列表是一個更難解決的問題,主要是因為文件夾通常不存在於 S3 中。 它們在邏輯上存在,但在物理上不存在,因為存在具有給定分層鍵的對象,例如dogs/small/corgi.png
。 有關想法,請參閱檢索 S3 存儲桶中的子文件夾名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.