You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python脚本将Bitbucket仓库文件复制到S3并保留目录结构?

解决Bitbucket目录结构同步到S3的问题

你的代码核心问题有两个:

  • 上传时仅使用文件名作为S3对象键,丢失了原有的目录层级
  • 调用upload_file时传入的file只是子目录下的文件名,不是完整路径,导致脚本找不到文件

修正后的代码会保留Bitbucket仓库的目录结构,同时确保文件能被正确找到并上传:

import os
import traceback

# 假设client_bucket、bucket_name、account_id已提前初始化
pwd = os.getcwd()
print(f"Current Dir is: {pwd}")
print("Files in the Directory: ")

for subdir, dirs, files in os.walk(pwd):
    for file in files:
        # 构造本地文件的完整路径
        local_file_path = os.path.join(subdir, file)
        # 计算文件相对于根目录的相对路径,作为S3的对象键(保留目录结构)
        relative_path = os.path.relpath(local_file_path, pwd)
        # 替换系统分隔符为S3兼容的正斜杠(Windows环境需要)
        object_name = relative_path.replace(os.sep, '/')
        
        print(f"Uploading {local_file_path} to s3://{bucket_name}/{object_name}")
        try:
            response = client_bucket.upload_file(local_file_path, bucket_name, object_name)
        except Exception as e:
            print(f"Error processing account {account_id}")
            for line in traceback.format_exc().splitlines():
                print(line)

关键修正点:

  • 用os.path.join(subdir, file)生成完整的本地文件路径,确保upload_file能定位到文件
  • 用os.path.relpath获取文件相对于仓库根目录的路径,作为S3的对象键,完美保留原目录结构
  • 额外处理了路径分隔符(Windows下是反斜杠,S3要求正斜杠),保证跨平台兼容

内容的提问来源于stack exchange,提问作者Navdeep

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 02:50:27