常用:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @mail    : lshan523@163.com
# @Time    : 2025/3/30 18:12
# @Author  : Sea
# @File    : s3upload.py# @Purpose :
# @history :
# pip install boto3
# ****************************
import os
import boto3
from botocore.exceptions import NoCredentialsError, PartialCredentialsError, ClientError

# Replace with your actual AWS Access Key and Secret Key
AWS_ACCESS_KEY = 'QDDASSOSDK4U  '   # AK
AWS_SECRET_KEY = 'ALDKLKDKLADLKADMLADMLADALSLLSLLSOC'    # SK
BUCKET_NAME = 'seatest'

def upload_file(TO_UPLOAD_FILE_PATH, S3_FILE_NAME):
    try:
        s3 = boto3.client(
            's3',
            aws_access_key_id=AWS_ACCESS_KEY,
            aws_secret_access_key=AWS_SECRET_KEY
        )
        # Upload the file
        s3.upload_file(TO_UPLOAD_FILE_PATH, BUCKET_NAME, S3_FILE_NAME)
        print(f'File {TO_UPLOAD_FILE_PATH} uploaded to {BUCKET_NAME}/{S3_FILE_NAME} successfully!')

    except FileNotFoundError:
        print("The file was not found.")
    except NoCredentialsError:
        print("Credentials not available.")
    except PartialCredentialsError:
        print("Incomplete credentials provided.")
    except Exception as e:
        print(f"An error occurred: {e}")



"""
list dir 
"""
def list():
    s3 = boto3.client(
        's3',
        aws_access_key_id=AWS_ACCESS_KEY,
        aws_secret_access_key=AWS_SECRET_KEY
    )
    response = s3.list_objects_v2(Bucket=BUCKET_NAME, Prefix="/")
    # 检查响应中是否有内容
    if 'Contents' in response:
        print("文件夹中的文件和对象:")
        for obj in response['Contents']:
            print(f"- {obj['Key']}")  # 打印文件/对象的键
    else:
        print("文件夹为空或不存在。")




def check_exist(bucket_name,file_key):
    # 创建 S3 客户端
    s3 = boto3.client(
        's3',
        aws_access_key_id=AWS_ACCESS_KEY,
        aws_secret_access_key=AWS_SECRET_KEY
    )
    # 定义存储桶名称和要检查的文件的键
    # bucket_name = 'your-bucket-name'
    # file_key = 'your/folder/yourfile.txt'  # 您要检查的文件路径
    try:
        # 尝试获取文件的头信息
        s3.head_object(Bucket=bucket_name, Key=file_key)
        print(f"文件 '{file_key}' 存在于存储桶 '{bucket_name}'。")
    except ClientError as e:
        # 检查错误代码
        if e.response['Error']['Code'] == '404':
            print(f"文件 '{file_key}' 不存在于存储桶 '{bucket_name}'。")
        else:
            print(f"发生了其他错误:{e}")




if __name__ == '__main__':
    list()
    # upload()
    file_name = 'sea_logo.png'
    s3_file_name = 'Report_Logo/CATI/CATIHK/'+file_name
    upload_file(file_name, s3_file_name)
    # check_exist("seatest","/Report_Logo/Sea/EG/SEA_SLI_Logo.png")

 

posted on 2025-03-30 18:50  lshan  阅读(22)  评论(0)    收藏  举报