我的Python逻辑出了什么问题?

问题描述:

我正在尝试为仓库管理项目创建一个目录编辑器,但每次尝试创建一个已创建的新文件夹,而不是处理像我在elif块中指定的问题时,它会给我这个错误:我的Python逻辑出了什么问题?

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

据我所知,我的if语句的基本逻辑没有错。

这里是我的代码:

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() 
+2

您需要首先检查** all **'directory_items'。这不是因为**第一**不相等,** **(或任何其他)不能相等。 –

你遍历目录内的项目 - 如果有一个文件夹是使用不同的名称比name,你会进入if分支,即使有也有一个文件夹那个名字。

最好的解决方案,恕我直言,是不是推倒重来,让蟒蛇检查是否存在对您的文件夹:

folder = path + name + "/" 

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

operation_chooserD() 

你似乎在目录中的新名称比较每个项目,这肯定会击中这个名字!= c条件(几次)。在这种情况下,循环是不需要的。

你可以尝试沿线的东西。

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

有几个与你的逻辑问题:

  • 试图在目录
  • 的为创建新的项目每项目如果/ elif的检查是多余的

你真正想要做的是这样的:

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

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

我猜directory_items是当前目录中文件名的列表。

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