首页 > 解决方案 > 文件创建者将文件夹名称识别为现有文件

问题描述

我编写了一个程序,它可以创建文件夹、文件并返回是否已创建文件夹/文件。例如,我在我的程序中创建了一个名为“test”的文件夹,然后当我在菜单上选择文件创建者并输入相同的名称时 - “test”程序告诉我他认识到这个文件已经存在但它并不真正存在。


import os
import sys

#1. creating file

def creatingFile():
    try:
       fileNames = []
       nameOfFile = input("Enter the name of file: ")
       fileNames.append(nameOfFile)
       if open(nameOfFile,"x") and nameOfFile != fileNames:
           print("file created.")
           sys.exit()
    except FileExistsError:
      print("file already exist.")
      creatingFile()
    except FileNotFoundError:
        print("please enter name of your file!")
        creatingFile()

#2. creating folder
def creatingFolders():
    try:
        while True:
            nameOfFolder = input("Please enter the name of folder: ")
            if nameOfFolder != "":
                creatingFolder = os.mkdir(nameOfFolder)
                print("Your folder has been created.")
                sys.exit()
            else:
                print("You didn't write the name of your folder. You'll be back to the very beginning of folder creator.")
                continue
    except FileExistsError:
        print("Folder already exists.")
        creatingFolders()

def Menu():
    while True:
        choice = input("What you want to create? File or Folder? ")
        if choice == "folder" or choice == "FOLDER" or choice == "Folder":
            creatingFolders()
        if choice == "file" or choice == "FILE" or choice == "File":
            creatingFile()
        if choice == "":
            print("Please select what you want to select!")
            continue

Menu()```

标签: python

解决方案


在 Windows 中,您不能创建具有相同名称的文件和文件夹,因此test 已经存在。


推荐阅读