python - 如何使用 python aioboto3 或 boto3 仅从 S3 获取文件?
问题描述
我有这段代码,我只想要以没有中间空文件夹的文件结尾的路径。例如:
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
不返回任何指示项是文件夹还是文件。所以,这看起来很实用。
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
推荐阅读
- python - 引用大型 JSON 文件的部分内容
- c# - FirebaseMessaging.TokenReceived 永远不会被触发
- radio-button - 聚合物键盘快捷键干扰单选按钮上现有的输入功能
- flutter - Flutter 自定义表情符号选择器
- linux - 从虚拟机(docker容器)发送通知到主机
- python - Conda 包未将环境放置在正确的路径中
- javascript - Firebase Cloud Firestore 规则允许获取但不允许列出
- sqlite - 无法在 SQLite 中自动分配 ID
- javascript - JavaScript:是否可以使用另一个变量的值来声明一个变量?
- python - 如何对 pandas DataFrame 进行切片,以便 pylance 不会给出返回类型为 NDFrame 的错误?