簡體   English   中英

如何使用python boto3獲取所有子目錄,除AWS S3中的文件外所有級別的深度

[英]How to get ALL subdirectories, all levels deep except files in AWS S3 with python boto3

有很多類似的問題,但我沒有找到這個問題的確切答案。 如何從初始目錄開始獲取所有子目錄。 子目錄的深度未知。

可以說我有:

data/subdir1/subdir2/file.csv
data/subdir1/subdir3/subdir4/subdir5/file2.csv
data/subdir6/subdir7/subdir8/file3.csv

所以我想要么得到所有長度都深的所有子目錄的列表,或者更好的是文件前一級的所有路徑。 在我的示例中,我希望得到:

data/subdir1/subdir2/
data/subdir1/subdir3/subdir4/subdir5/
data/subdir6/subdir7/subdir8/

但我也可以使用它:

data/subdir1/
data/subdir1/subdir2/
data/subdir1/subdir3/
data/subdir1/subdir3/subdir4/
etc...
data/subdir6/subdir7/subdir8/

到目前為止,我的代碼只能讓我獲得一級目錄深度:

result = await self.s3_client.list_objects(
    Bucket=bucket, Prefix=prefix, Delimiter="/"
)

subfolders = set()
for content in result.get("CommonPrefixes"):
    print(f"sub folder : {content.get('Prefix')}")
    subfolders.add(content.get("Prefix"))

return subfolders
import os

# list_objects returns a dictionary. The 'Contents' key contains a
# list of full paths including the file name stored in the bucket
# for example: data/subdir1/subdir3/subdir4/subdir5/file2.csv
objects = s3_client.list_objects(Bucket='bucket_name')['Contents']

# here we iterate over the fullpaths and using 
# os.path.dirname we get the fullpath excluding the filename
for obj in objects:
    print(os.path.dirname(obj['Key'])

為了使其成為目錄“路徑”的唯一排序列表,我們將使用 sort a set comprehension inline。 集合是唯一的,sorted 會將其轉換為列表。

請參閱https://docs.python.org/3/tutorial/datastructures.html#sets

import os
paths = sorted({os.path.dirname(obj['Key']) for obj in objects})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM