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

2024-04-25 12:42:18 发布

您现在位置: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”…)是否已经存在:

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

谢谢你

根据编程语法,'directory'和'folder'之间有什么区别吗?在


Tags: 文件topath代码nameproject文件夹名称
3条回答

首先,directory和{}是同义词,因此您要查找的检查与您已经使用过的相同,即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)

希望这段代码能帮你解决这个问题。在

你可以使用手术室步行函数获取所有目录的列表以检查 现有或子文件夹1(2)或子文件夹。然后你可以使用操作系统实际上,命令是用来删除命令的。这是一个粗略的解决方案,但希望这能有所帮助。在

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

经过一段时间的练习,我终于想到了一个密码:

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)

感谢所有激励我的人,特别是回答我最初问题的人。在

相关问题 更多 >