Python 问题,第一个 if 语句不是 运行 when bucket_name matches a item in bucket list

Python question, first if statement not running when bucket_name matches an item in bucket list

#1 激活 Boto 以供使用并将其定向到 s3 存储

import boto3
s3 = boto3.resource('s3')

#2 Python 要求用户创建存储桶名称

  bucket_name = input("Select a bucket name (must be all lowercase).  ")

#3 Python 在 s3 中收集桶名称并打印列表

for bucket in s3.buckets.all():
    print(bucket.name)
bucket = list(s3.buckets.all())

#4 使用 s3 检查 bucket_name 是否匹配任何名称, 通知他们是否匹配,并要求创建另一个名称。如果名字 它不会创建一个具有新的唯一名称的新存储桶。

if bucket_name in bucket:
    print("The name you selected is already taken, please choose a different name")
    bucket_name = input('Select another bucket name (must be all lowercase).  ')
else:
    print('Your new bucket is named',bucket_name,"!")
    def create_bucket():
        s3_client = boto3.client('s3')
        s3_client.create_bucket(Bucket=bucket_name)
    create_bucket()

首先用下面的代码提取所有的buckets名称。

import boto3
s3 = boto3.resource('s3')

bucket_name = input("Select a bucket name (must be all lowercase).  ")

all_buckets = [bucket.name.lower() for bucket in s3.buckets.all()]

现在检查其中是否存在 bucket_name。

if bucket_name in all_buckets:
    print("The name you selected is already taken, please choose a different name")
    # Your rest of the logic goes here.

这将 运行 并使用您的逻辑搜索每个输入的名称,直到您退出。输入将自动降低.lower()

import boto3
s3 = boto3.resource('s3')
bucketNames = [bucket.name for bucket in s3.buckets.all()]

def create_bucket(bucket_name):
    s3_client = boto3.client('s3')
    s3_client.create_bucket(Bucket=bucket_name)

while True:
    bucket_name = input("Write a bucket name (q to quit):  ").lower()
    if bucket_name not in bucketNames:
        print(f'Your new bucket is named {bucket_name}!')
        create_bucket(bucket_name)
    else:
        print("The name you wrote is already taken, try a different name")
        bucket_name = input('Write a bucket name (q to quit):  ').lower()
    if bucket_name == "q" or bucket_name == "quit":
        break

这应该有效:

import boto3

def create_bucket(bucket_name):
    s3_client = boto3.client('s3')
    s3_client.create_bucket(Bucket=bucket_name)

bucket_name = input("Select a bucket name (must be all lowercase).")

s3 = boto3.resource('s3')
all_buckets = list(s3.buckets.all())

if bucket_name in all_buckets:
    print("The name you selected is already taken, please choose a different name")
    bucket_name = input('Select another bucket name (must be all lowercase).  ')
else:
    print('Your new bucket is named',bucket_name,"!")
    create_bucket(bucket_name)