Iain Davis
Iain Davis

Reputation: 11

What's going wrong with my python logic?

I'm attempting to create a directory editor for a warehouse managing project, but every time I try to create a new folder that has already been created, rather than handling the problem like I specify in the elif block it gives me this error :

FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'C:/Users/User_Name/Documents/Warehouse_Storage/folder_name'

As far as I can tell, there's nothing wrong with the base logic of my if statement.

Here's my code:

if operation.lower() == "addf" :

    name = input("What would you like to name your new folder? \n")

    for c in directory_items :
        if name != c :
            os.makedirs(path + name + "/")
            operation_chooserD()

        elif name == c:
            print("You already created a folder with this name.")
            operation_chooserD()

Upvotes: 1

Views: 70

Answers (4)

Rudra Shailesh
Rudra Shailesh

Reputation: 46

I guess directory_items is list of file names in current directory.

if operation.lower() == "addf" :

    name = input("What would you like to name your new folder? \n")
    print(directory_items)
    # check here what you are getting in this list, means directory with / or not. If you are getting
    if name not in directory_items:
        os.makedirs(path + name + "/")
        operation_chooserD()
    else:
        print("You already created a folder with this name.")
        operation_chooserD()

Upvotes: 0

Tague Griffith
Tague Griffith

Reputation: 4173

There are a couple of problems with your logic:

  • Attempting to create the new item for every item in the directory
  • The if/elif test is redundant

What you really want to do is something like:

if c not in directory_items:
    os.makedirs(path + name + "/")
    operation_chooserD()

else: 
    print("You already created a folder with this name.")
    operation_chooserD()

Upvotes: 1

buckettt
buckettt

Reputation: 319

You seem to be comparing your new name to every item in the directory, this will definitely hit the name!=c condition (several times). In this case the loop is unnecesary.

YOu can try something along the line of.

if name in c:
//do stuff if name exists
else:
//create the directory

Upvotes: 0

Mureinik
Mureinik

Reputation: 311308

You're iterating over the directory items - if there's a folder with a different name than name, you'll enter the if branch, even if there's also a folder with that name.

The best solution here, IMHO, is to not reinvent the wheel, and let python check if the folder exists for you:

folder = path + name + "/"

if os.path.exists(folder):
    print("You already created a folder with this name.")
else:
    os.makedirs(folder)

operation_chooserD()

Upvotes: 0

Related Questions