您可以使用Python的boto3库来与Amazon S3进行交互,并使用zipfile库来创建和压缩.zip文件。以下是一个示例代码,演示如何从Amazon S3下载.mp3和.wav文件,并将它们压缩为.zip文件。
import boto3
import zipfile
def download_files_from_s3(bucket_name, file_extensions):
s3 = boto3.client('s3')
file_list = []
# 获取指定后缀的文件列表
response = s3.list_objects_v2(Bucket=bucket_name)
for obj in response['Contents']:
if obj['Key'].endswith(file_extensions):
file_list.append(obj['Key'])
# 下载文件并保存到本地
for file in file_list:
s3.download_file(bucket_name, file, file)
return file_list
def create_zip_file(file_list):
with zipfile.ZipFile('downloaded_files.zip', 'w') as zipf:
for file in file_list:
zipf.write(file)
bucket_name = 'your_bucket_name'
file_extensions = ('.mp3', '.wav')
# 下载文件
downloaded_files = download_files_from_s3(bucket_name, file_extensions)
# 创建.zip文件
create_zip_file(downloaded_files)
请记得将your_bucket_name替换为您自己的S3存储桶名称。