【问题标题】:copy files between s3 buckets using python使用 python 在 s3 存储桶之间复制文件
【发布时间】:2021-07-03 21:27:55
【问题描述】:

我有一个包含 3 个字段(路径、文件夹结构、文件名)的元数据的 excel 表

Path:源文件在s3 source bucket中的路径 folder_structure:Target bucket 中需要新建的文件夹结构 文件名:这是复制到目标桶后需要重命名的文件名

我有以下代码在 Windows 源文件夹中工作并创建目标文件夹并将数据复制到目标文件夹。需要将其修改为从 s3 存储桶获取并加载另一个 s3 存储桶。

代码:

将熊猫导入为 pd 导入操作系统,shutil 从路径库导入路径

data = pd.read_excel('c:\data\sample_requirement.xlsx',engine='openpyxl')

root_dir = '来源'

对于范围内的记录(len(数据)):

#Replacing the '|' symbol with backward slash
dire = data['folder_structure'][rec].replace('|','\\')

#appending root directory with folder structure
directory = root_dir+'\\'+dire
#print(directory)

#Checking if path exists, if exit-> skip else-> create new
if not os.path.exists(directory):
    #print('Not exist')
    
    #creating new directory
    os.makedirs(directory)

#Path in the excel
path = data['path'][rec]

#Filenames to change
filename = data['filename'][rec]
#print(filename)

if not os.path.isfile(directory + filename) :

    #Copying the files to created path
    shutil.copy(path,directory)

    #Renaming the files
    try: 
        os.rename(directory + os.path.basename(path),directory + filename)
    except FileExistsError as e:
        print('File Name already Exists')

【问题讨论】:

    标签: python amazon-web-services amazon-s3


    【解决方案1】:

    如何将其添加到您的代码中替换您的目标和目标存储桶:-

    import boto3
    s3 = boto3.resource('s3')
    copy_source = {
        'Bucket': 'yoursourcebucket',
        'Key': 'yourkey'
    }
    s3.meta.client.copy(copy_source, 'nameofdestinationbucket', 'destinationkey')
    

    遵循文档了解代码的the details 是一个好习惯,还请注意可能还有许多其他方法可以执行相同的操作,例如使用 awscli https://stackoverflow.com/a/32526487/13126651

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-07
      • 2020-06-24
      • 2021-07-17
      • 1970-01-01
      • 2016-11-05
      • 2018-01-06
      • 2017-11-23
      • 2019-08-07
      相关资源
      最近更新 更多