安装COS Python SDK的代码为:

# ! pip install -U cos-python-sdk-v5

Python上传

from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
from qcloud_cos import CosServiceError
from qcloud_cos import CosClientError

import sys
import os

secret_id = 'AKIDabcdefg'     # secret_id
secret_key = 'CAabcdefg'     # secret_key
region = 'ap-nanjing'    # 用户的region
token = None               # 使用临时密钥需要传入Token,默认为空,可不填
config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=token)  # 获取配置对象
client = CosS3Client(config)

bucket = 'bucketname-userid' # Bucket名字
folder_path = '1/' # 本地文件夹名字,以/结尾
prefix = '/models/' # Bucket里面的prefix

def upload_recursive(folder_path, no_use_folder_prefix, bucket, prefix):
    assert no_use_folder_prefix.endswith('/')
    for file in os.listdir(folder_path):
        # print(os.path.join(folder_path, file))
        
        local_file_name = os.path.join(folder_path, file)
        clean_use_file_name = os.path.join(folder_path, file).replace(no_use_folder_prefix, '')
        cos_file_name = os.path.join(prefix, os.path.join(folder_path, file).replace(no_use_folder_prefix, ''))
        
        try:
            os.listdir(os.path.join(folder_path, file))
            upload_recursive(os.path.join(folder_path, file), no_use_folder_prefix, bucket, prefix)
        except:
            print('Uploading',cos_file_name)
            response = client.put_object_from_local_file(
                Bucket=bucket,
                LocalFilePath=local_file_name,
                Key=cos_file_name,
            )
            # print(response['ETag'])

upload_recursive(folder_path, folder_path, bucket, prefix)
最后修改:2021 年 06 月 01 日 02 : 25 PM
如果觉得我的文章对你有用,请随意赞赏