2017-02-22 57 views
1

我正在嘗試爲倉庫管理項目創建一個目錄編輯器,但每次嘗試創建一個已創建的新文件夾,而不是處理像我在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'。這不是因爲**第一**不相等,** **(或任何其他)不能相等。 –

回答

0

你遍歷目錄內的項目 - 如果有一個文件夾是使用不同的名稱比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() 
0

你似乎在目錄中的新名稱比較每個項目,這肯定會擊中這個名字!= c條件(幾次)。在這種情況下,循環是不需要的。

你可以嘗試沿線的東西。

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

有幾個與你的邏輯問題:

  • 試圖在目錄
  • 的爲創建新的項目每項目如果/ 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() 
0

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