简体   繁体   English

Python递归删除目录中的文件/文件夹,但不删除父目录或特定文件夹

[英]Python recursively remove files/folders in a directory, but not the parent directory or a specific folder

This type of question has been asked before, but I can't seem to get exactly what I want through the help I've found.以前有人问过这种类型的问题,但我似乎无法通过我找到的帮助确切地得到我想要的。

This question has an answer by user Iker , where the user gives code that does work exactly as intended: it removes all the files and directories from a folder, but not the parent folder itself. 这个问题有一个由用户卡西利亚斯的回答,其中用户提供了代码,的工作完全按照预期:它从文件夹中删除所有的文件和目录,但不是父文件夹本身。

I want to tweak this further by deleting all the files from a parent directory, but not the parent directory, and I want to exclude a folder within the directory.我想通过从父目录中删除所有文件而不是父目录来进一步调整,我想排除目录中的一个文件夹。

The code I am using is:我正在使用的代码是:

import os
import shutil

files = '[the path to my folder]'

for root, dirs, files in os.walk(files):
    for f in files:
        os.unlink(os.path.join(root, f))
    for d in dirs:
        shutil.rmtree(os.path.join(root, d))

I have tried adding an "If" statement after the "for" statement that basically says:我尝试在“for”语句之后添加一个“If”语句,它基本上说:

if files != keep如果文件 != 保留

and I have a variable "keep" pointing to a folder in the parent file called "keep," so that this script will delete everything except the parent directory and the directory called "keep" within the parent.并且我有一个变量“keep”指向父文件中名为“keep”的文件夹,因此该脚本将删除除父目录和父目录中名为“keep”的目录之外的所有内容。 However, after adding that, the code does not work.但是,添加后,代码不起作用。

Here is the exact code I had, with the if statement that breaks the code:这是我拥有的确切代码,其中 if 语句破坏了代码:

import os
import shutil

files = '[the path to the parent folder'
keep = '[the path to the "keep" folder]'

for root, dirs, files in os.walk(files):
    for f in files:
        if files != keep:
            os.unlink(os.path.join(root, f))
    for d in dirs:
        if files != keep:
            shutil.rmtree(os.path.join(root, d))

I'm sure what I'm doing is very obvious, but it is not obvious to me, so any help will be appreciated.我确定我在做什么很明显,但对我来说并不明显,所以任何帮助将不胜感激。

Thanks!谢谢!

EDIT : Based on Ben's answer below, here is the code that worked for me:编辑:根据下面 Ben 的回答,这是对我有用的代码:

import os
import shutil

root_dir = r'[path to directory]' # Directory to scan/delete

keep = 'keep' # name of file in directory to not be deleted

for root, dirs, files in os.walk(root_dir):
    for name in files:
        # make sure what you want to keep isn't in the full filename
        if (keep not in root and keep not in name):
            os.unlink(os.path.join(root, name)) # Deletes files not in 'keep' folder
    for name in dirs:
        if (keep not in root and keep not in name):
            shutil.rmtree(os.path.join(root, name)) # Deletes directories not in 'keep' folder

Modified Version: It may help if you are using Windows OS修改版本:如果您使用的是 Windows 操作系统,可能会有所帮助

import os
import shutil

root_dir = r'C:\Users\Venus\scarap'

for root, dirs, files in os.walk(root_dir):

    for name in files:
            print(os.path.join(root, name)) 
            os.remove(os.path.join(root, name))
    for name in dirs:
            print(os.path.join(root, name))
            shutil.rmtree(os.path.join(root, name))

I would not check equality, but whether your path contains the folder you want to keep.我不会检查相等性,而是检查您的路径是否包含您要保留的文件夹。 This example is adapted from the docs (scroll up a little to see it)这个例子改编自文档(向上滚动一点可以看到)

import os

# change this, obviously
root_dir = r'C:\Users\ben\Documents\Python Scripts\tmp'

keep = 'keep'

for root, dirs, files in os.walk(root_dir):
    for name in files:
        # make sure what you want to keep isn't in the full filename
        if (keep not in root and keep not in name):
            print(os.path.join(root, name)) #change to os.remove once sure
    for name in dirs:
        if (keep not in root and keep not in name):
            print(os.path.join(root, name)) # change to os.rmdir once sure

Note: depending on how detailed your keep is, this might not erase some files you want to erase: rm_me\\keep.txt will be kept even though it's not in the right directory.注意:根据您keep详细程度,这可能不会删除您要删除的某些文件: rm_me\\keep.txt将被保留,即使它不在正确的目录中。 Detailed folder names can help with this: if keep is something like r'C:\\very_specific' , that won't be the name of a file, and you'll erase everything you need.详细的文件夹名称可以帮助解决这个问题:如果 keep 是类似r'C:\\very_specific'东西,那不会是文件的名称,您将删除您需要的所有内容。

a quick and dirty approach:一种快速而肮脏的方法:

  • use shutil.rmtree to destroy the directory and its contents使用shutil.rmtree销毁目录及其内容
  • re-create the top directory重新创建顶层目录

it may create the new top directory with other permissions, though, or may fail if the directory is write protected, but in most cases it will be ok.但是,它可能会创建具有其他权限的新顶级目录,或者如果目录被写保护可能会失败,但在大多数情况下它会没问题。

import shutil,os

root = r"C:\path\to\root"
shutil.rmtree(root)
os.mkdir(root)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 递归地将文件从子目录移动到父目录中的文件夹 - Recursively move files from subdirectory to folders in parent directory 递归下载目录中的特定文件 - Download specific files in a directory recursively 将文件夹目录中的所有.csv文件复制到python中的一个文件夹 - Copy all .csv files in a directory of folders to one folder in python 递归搜索目录中具有特定扩展名的文件 - Recursively searching for files with specific extensions in a directory 相当于python 3中的find coreutil命令,用于递归返回目录结构中的所有文件和文件夹? - equivalent to the find coreutil command in python 3 for recursively returning all files and folders in a directory structure? 使用 python os.walk 如何检查目录名并仅处理特定目录中的那些文件(递归)? - Using python os.walk how to check for directory name and only process those files (recursively) in the specific directory? (python)以递归方式从目录结构中删除大小写? - (python) recursively remove capitalisation from directory structure? PathLib 递归删除目录? - PathLib recursively remove directory? 在Python中递归地将行追加到目录中的所有文件 - Append Line to All Files in a Directory Recursively in Python Python脚本以递归方式打开目录中的.rar文件 - Python script to recursively open .rar files in a directory
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM