有很多類似的問題,但我沒有找到這個問題的確切答案。如何從初始目錄開始獲取所有子目錄。子目錄的深度未知。
可以說我有:
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
uj5u.com熱心網友回復:
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。集合是唯一的,排序后會將其轉換為串列。
請參閱https://docs.python.org/3/tutorial/datastructures.html#sets
import os
paths = sorted({os.path.dirname(obj['Key']) for obj in objects})
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/318819.html
標籤:Python 亚马逊网络服务 亚马逊-s3 boto3
上一篇:如何使用pythonaioboto3或boto3僅從S3獲取檔案?
下一篇:當使用geom_smooth來繪制一條最佳擬合線時,我得到了。`stat_smooth()`:invalid'x'typein'x||y'inR
