python - Python Boto3 - 如何删除“文件夹”并重命名另一个?
问题描述
我在 S3 中有这些路径:
s3://mykey/mytest/file1.txt
s3://mykey/mytest/file2.txt
s3://mykey/mytest/file3.txt
和
s3://mykey/mytest_temp/file4.txt
s3://mykey/mytest_temp/file5.txt
s3://mykey/mytest_temp/file6.txt
想要删除s3://mykey/mytest/
(以及其中的所有文件)
然后重命名s3://mykey/mytest_temp/
为,s3://mykey/mytest/
同时将所有文件保留在其中(file4, file5, file6
)。
最终结果应该是 - 只有 1 folder
:
s3://mykey/mytest/file4.txt
s3://mykey/mytest/file5.txt
s3://mykey/mytest/file6.txt
如何使用Python Boto3
?
谢谢。
解决方案
要使用 boto3 纯粹从 Python 执行此操作,您需要执行以下操作:
删除现有的“文件夹”
- 调用
list_objects_v2()
,传入一个前缀来获取目录列表 - 获取结果并将对象名称传递给
delete_objects()
调用
请注意,这些 API 调用中的每一个都最多可处理 1000 个对象。如果您有超过 1000 个对象,则需要通过再次调用它们来对结果进行分页。
“重命名”对象
Amazon S3 没有“重命名”命令。相反,有必要将每个对象复制到一个新键,然后删除原始对象。
- 调用
list_objects_v2()
,传入一个前缀来获取目录列表 - 循环遍历每个对象并:
- 调用,在目标 Key 中
copy_object()
指定完整路径 delete_object()
复制对象后调用
- 调用,在目标 Key 中
推荐阅读
- vba - 如何修复计算机锁定时发生的错误?
- google-chrome - 按钮未在 chrome 中显示,但在 safari 中显示
- javascript - 我无法使用 request-promise 发布
- pine-script - “过去 n 天”的最高点,而不是“n 天前”
- azure - ARM 模板,段长度不正确
- angular - 在 Angular 项目中使用带有 ngx-leaflet 地图的 heatmap.js 插件更改半径
- c# - 索引属性的 INotifyPropertyChanged
- python - 如何在 Python 中为多行正则表达式 sub (re.sub)?
- c# - 如何从局部变量中保持位置?
- node.js - NodeJS:用 JavaScript 内容编写 http 响应