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

3

我之前并没有太多关于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”之间是否存在差异?

2
“一个我不知道如何编写的条件,用于检查这些文件夹('1'、'2'、'3'等)是否已经存在。”但是……你已经使用os.path.exists(path_to_folders)完成了这个任务……问题出在哪里? - Aran-Fey
3个回答

3

希望这段代码可以帮助你解决问题。

你可以使用os.walk函数获得所有目录的列表,以检查子文件夹(1或2或3)是否存在。然后,你可以使用os.system来启动命令提示符命令,并使用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 ")

1
首先,directoryfolder 是同义词,所以你正在寻找的检查与你已经使用的相同,即 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)

0

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

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)

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接