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

Viewed 68

#1 Activates Boto for use and directs it to s3 storage

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

#2 Python ask user to create a bucket name

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

#3 Python gathers bucket names within s3 and prints list

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

#4 Checks bucket_name against the names with s3 to see if it matches any names, informs them if there is a match, and ask to create another name. If the name doesn't it create a new bucket with new unique 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()
3 Answers

First extract all the buckets names with the following code.

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()]

Now check for the bucket_name present in it or not.

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.

This will run and search for every entered name using your logic until you quit. Input will automatically be lowered with .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

This should work:

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)
Related