【问题标题】:'NoneType' object is not iterable loop to get folder in boto3'NoneType' 对象不是在 boto3 中获取文件夹的可迭代循环
【发布时间】:2021-08-13 06:20:10
【问题描述】:

我尝试循环获取当前文件,例如ap-sounteast/2021/02/12,我得到了所有区域并输入了年、月、日但不工作

然后我尝试2021/ 并没有同样的原因

我的代码有什么问题?

year = now.strftime("%Y")
month = now.strftime("%m")
day = now.strftime("%d")

account = bucket.meta.client.list_objects(Bucket=bucket.name, Prefix='AWSLogs/', Delimiter='/')
for account in account.get('CommonPrefixes'):
    list_account = account.get('Prefix')

    region = bucket.meta.client.list_objects(Bucket=bucket.name, Prefix=(list_account+'CloudTrail/'), Delimiter='/')
    for region in region.get('CommonPrefixes'):
      region = region.get('Prefix')

      files = bucket.meta.client.list_objects(Bucket=bucket.name, Prefix=(region+year+'/'+month+'/'+day+'/'), Delimiter='/')
      for files in files.get('CommonPrefixes'):
        files = files.get('Prefix')
        print (files) 

错误

      9       files = bucket.meta.client.list_objects(Bucket=bucket.name, Prefix=(region+year+'/'+month+'/'+day+'/'), Delimiter='/')
---> 10       for files in files.get('CommonPrefixes'):
     11         files = files.get('Prefix')
     12         print (files)

TypeError: 'NoneType' object is not iterable

谢谢

【问题讨论】:

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


【解决方案1】:

当你想运行一个for循环时,你需要在'iterable'对象上运行它,比如列表和数组。您尝试执行 for files in files.get('CommonPrefixes'): 循环遍历 CommonPrefixes 文件。该文件似乎是无类型的。

如果你做print(type(files.get('CommonPrefixes')),你可以检查它是什么类型。

您需要替换 files.get('CommonPrefixes')。如果您确定这是您想要的文件,请尝试将其转换为数组或列表。

【讨论】:

    【解决方案2】:

    我尝试不同的方式,它的工作

            region = (region.get('Prefix')+year+'/'+month+'/'+day+'/')
            
            files = list(bucket.objects.filter(Prefix=region))
            for i in range(0, len(files)):
              getfile = (files[i].key)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-10
      • 1970-01-01
      • 2016-02-08
      • 2020-05-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多