如何删除 Python 中具有特定名称的文件夹?

How to delete folders with specific names in Python?

我没有太多地使用 Python 文件 I/O,现在我想请求你的帮助。

我想删除所有具有特定名称的文件夹,例如'1', '2', '3', ... 我用代码创建了它们:

zoom_min = 1
path_to_folders = 'D:/ms_project/'
def folders_creator(zoom):
     for name in range (zoom_min, zoom + 1):
        path_to_folders = '{0}'.format(name)
         if not os.path.exists(path_to_folders):
             os.makedirs(path_to_folders)

我希望我的 Python 代码有一个我不知道如何写的条件,它检查这些文件夹('1'、'2'、'3'...)是否已经存在:

如果是,我想删除它们及其所有内容,然后执行上面的代码。 如果没有,那么就执行代码。

P.S。根据编程语法,'directory' 和 'folder' 之间是否存在任何差异?

希望这段代码能帮助您解决这个问题。

您可以使用os.walk函数获取所有目录的列表来检查是否 子文件夹(1 或 2 或 3)存在。然后你可以使用 os.system ,它基本上允许你启动 cmd 命令并使用 delete 命令。这是一个粗略的解决方案,但希望对您有所帮助。

import os

# purt r"directorypath" within os.walk parameter.

genobj = os.walk(r"C:\Users\Sam\Desktop\lel") #gives you a generator function with all directorys
dirlist = genobj.next()[1] #firt index has list of all subdirectorys
print dirlist 

if "1" in dirlist: #checking if a folder called 1 exsists
    print "True"


#os.system(r"rmdir /S /Q your_directory_here ")

首先 directoryfolder 是同义词,因此您要查找的支票与您已经使用过的相同,即。 e. os.path.exists.

删除目录(及其所有内容)的最简单方法可能是使用标准模块 shutil 提供的函数 rmtree

以下是您的代码,其中包含我的建议。

import shutil
zoom_min = 1
path_to_folders = 'D:/ms_project/'

def folders_creator(zoom):
    for name in range (zoom_min, zoom + 1):
        path_to_folders = '{0}'.format(name)
        if os.path.exists(path_to_folders):
            shutil.rmtree(path_to_folders) 
        os.makedirs(path_to_folders)

经过一段时间的练习,我最终得到了一个在我脑海中的代码:

def create_folders(zoom):
    zoom_min = 1
    path_to_folders = 'D:/ms_project/'

    if os.path.isdir(path_to_folders):

        if not os.listdir(path_to_folders) == []:

            for subfolder in os.listdir(path_to_folders):
                subfolder_path = os.path.join(path_to_folders, subfolder)

                try:
                    if os.path.isdir(subfolder_path):
                        shutil.rmtree(subfolder_path)

                    elif os.path.isfile(subfolder_path):
                        os.unlink(subfolder_path)

                except Exception as e:
                    print(e)

        elif os.listdir(path_to_folders) == []:
           print("A folder existed before and was empty.")

    elif not os.path.isdir(path_to_folders):
        os.mkdir("ms_project")

    os.chdir(path_to_folders)

    for name in range(zoom_min, zoom + 1):
        path_to_folders = '{0}'.format(name)

        if not os.path.exists(path_to_folders):
            os.makedirs(path_to_folders)

感谢所有启发我的人,尤其是那些回答我最初问题的人。