我使用python 2.7.x和Boto API 2.X连接到AWS S3存储桶。我有一个独特的情况,我想从S3存储桶下载来自特定目录/文件夹的文件myBucket/foo/
。但问题是我想在S3文件夹中留下最新的文件,而不是下载它。有一次,我在本地邮箱上下载这些文件,我想将这些文件移到同一个文件夹下的另一个文件夹myBucket/foo/bar/
。有没有人曾经在类似情况下工作过?
以下是一些解释:
我的S3存储桶:事件日志 将从中下载文件的S3存储桶上的文件夹路径:
event-logs/apps/raw/source_data/
S3存储桶上将移动(存档)下载文件的文件夹路径:
event-logs/apps/raw/archive_data/
注意:“event-logs / apps / raw /”路径在同一个桶中是常见的
所以,如果我在S3上的source_data文件夹下有5个文件:
s3://event-logs/apps/raw/source_data/data1.gz
event-logs/apps/raw/source_data/data2.gz
event-logs/apps/raw/source_data/data3.gz
event-logs/apps/raw/source_data/data4.gz
event-logs/apps/raw/source_data/data5.gz
我需要将前4个文件(最旧的文件)下载到我的本地计算机并保留最新文件I.e. data5.gz
落后。下载完成后,将这些文件从S3 ../source_data
文件夹移动到同一S3存储桶下的../Archive_data
文件夹,并从原始source_data文件夹中删除。这是我的代码,列出S3中的文件,然后下载文件,然后删除文件。
AwsLogShip = AwsLogShip(aws_access_key, aws_secret_access_key, use_ssl=True)
bucket = AwsLogShip.getFileNamesInBucket(aws_bucket)
def getFileNamesInBucket(self, aws_bucket):
if not self._bucketExists(aws_bucket):
self._printBucketNotFoundMessage(aws_bucket)
return list()
else:
bucket = self._aws_connection.get_bucket(aws_bucket)
return map(lambda aws_file_key: aws_file_key.name, bucket.list("apps/raw/source_data/"))
AwsLogShip.downloadAllFilesFromBucket(aws_bucket, local_download_directory)
def downloadFileFromBucket(self, aws_bucket, filename, local_download_directory):
if not self._bucketExists(aws_bucket):
self._printBucketNotFoundMessage(aws_bucket)
else:
bucket = self._aws_connection.get_bucket(aws_bucket)
for s3_file in bucket.list("apps/raw/source_data"):
if filename == s3_file.name:
self._downloadFile(s3_file, local_download_directory)
Break;
AwsLogShip.deleteAllFilesFromBucket(aws_bucket)
def deleteFilesInBucketWith(self, aws_bucket, filename):
if not self._bucketExists(aws_bucket):
self._printBucketNotFoundMessage(aws_bucket)
else:
bucket = self._aws_connection.get_bucket(aws_bucket)
for s3_file in filter(lambda fkey: filename(fkey.name), bucket.list("apps/raw/source_data/")):
self._deleteFile(bucket, s3_file)
我真正想要达到的目标是:
答案 0 :(得分:0)
这就是我解决这个问题的方法!
bucket_list = bucket.list(prefix='Download/test_queue1/', delimiter='/')
list1 = sorted(bucket_list, key= lambda item1: item1.last_modified)
self.list2 = list1[:-1]
for item in self.list2:
self._bucketList(bucket, item)
def _bucketList(self,bucket, item):
print item.name, item.last_modified