[英]Getting size of every folder and sub-folder in S3 using Python boto3
[英]how to upload sub-folder which is empty to S3 using python
以下代碼可以正常工作,除非存在一個子文件夾,該子文件夾中沒有任何文件,則該子文件夾不會出現在S3中。 例如,如果/ home / temp / subfolder沒有文件,則子文件夾不會在S3中顯示。 如何更改代碼,以便在S3中也上傳空文件夾? 我試圖寫某事。 (請參閱下面的注釋),但不知道如何將put_object()調用到空子文件夾。
#!/usr/bin/env python
import os
from boto3.session import Session
path = "/home/temp"
session = Session(aws_access_key_id='XXX', aws_secret_access_key='XXX')
s3 = session.resource('s3')
for subdir, dirs, files in os.walk(path):
# note: if not files ......
for file in files:
full_path = os.path.join(subdir, file)
with open(full_path, 'rb') as data:
s3.Bucket('my_bucket').put_object(Key=full_path[len(path)+1:],
Body=data)
此外,我嘗試調用此函數來檢查子文件夾或文件是否存在。 它適用於文件,但不適用於子文件夾。 如何檢查子文件夾是否存在? (如果存在子文件夾,我將不會上傳)
def check_exist(s3, bucket, key):
try:
s3.Object(bucket, key).load()
except botocore.exceptions.ClientError as e:
return False
return True
順便說一句,我從上面引用了上面的代碼
和
http://www.developerfiles.com/upload-files-to-s3-with-python-keeping-the-original-folder-structure/
感謝他們分享代碼。
目錄(文件夾,子文件夾等)在S3中不存在。
當您將此文件復制到空的S3存儲桶/mydir/myfile.txt
,僅將文件myfile.txt
復制到S3。 未創建目錄mydir
因為該字符串是文件名mydir/myfile.txt
。 實際文件名是完整路徑,不存在或未創建任何子目錄。
在存儲桶中列出文件時,S3通過使用前綴來模擬目錄。 如果指定mydir/
,則將返回所有以mydir/
開頭的S3對象,包括mydir/anotherfolder/myotherfile.txt
。 S3支持定界符(例如/
以便可以創建子目錄的外觀。
注意:S3對象的文件名開頭沒有/
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.