当给定路径时,在S3中搜索文件

2024-09-21 05:55:37 发布

您现在位置:Python中文网/ 问答频道 /正文

给定一个到S3 bucket的路径,我需要在同一路径中找到另一个文件并处理它

  • 我在Python中使用Django
  • 我有一个名为“HouseList”的模型和一个名为“CustomerFile”的模型
  • 我使用的函数返回需要修改的HouseList对象列表

对于那里的每个对象,我都有一个文件路径,在该路径中,我可以找到相应的客户文件,正如您在终端的这些打印中看到的:

In [7]: HouseList.objects.get(id=11508).file_path
Out[7]: u'85/1545927/omc_emea_hl_small.csv'

In [8]: CustomerFile.objects.get(id=5031).file_path
Out[8]: u'85/1545927/omc_emea_pos_small.csv'

有没有一种方法,在给定路径前缀的情况下,获取位于该路径的所有文件的列表


Tags: 文件path对象in模型路径id列表
2条回答

^{}函数可以返回给定前缀的对象列表:

response = client.list_objects_v2(
    Bucket='string',
    Delimiter='string',
    EncodingType='url',
    MaxKeys=123,
    Prefix='string',
    ContinuationToken='string',
    FetchOwner=True|False,
    StartAfter='string',
    RequestPayer='requester'
)

所以,你可以用这样的方法:

path = HouseList.objects.get(id=11508).file_path

response = client.list_objects_v2(
    Bucket=your_bucket,
    Prefix=path[:path.rfind('/')+1],
)

您可以使用Python中的s3boto模块列出具有给定前缀的文件:http://boto.cloudhackers.com/en/latest/ref/s3.html#boto.s3.bucket.Bucket.list

prefix (string) – allows you to limit the listing to a particular prefix. For example, if you call the method with prefix=’/foo/’ then the iterator will only cycle through the keys that begin with the string ‘/foo/’.

相关问题 更多 >

    热门问题