简体   繁体   English

如何通过使用文件夹内容作为参考删除文件夹?

[英]How to delete a folder by using its contents as a reference?

I need to delete a folder and its contents, and while the contents are consistent, the folder name has no pattern with which to fall on. 我需要删除一个文件夹及其内容,并且在内容一致的同时,该文件夹名称没有任何可依赖的模式。 In the path defined in the below code, another folder exists, and that folder always has a file with extension ".cax": 在以下代码定义的路径中,存在另一个文件夹,并且文件夹始终具有扩展名为“ .cax”的文件:

import os
myfile_path = "H:/PythonTools/test/exampleA"
for root, dirs, files in os.walk(myfile_path):
    for file in files:
        if file.endswith(".cax"):
            print(os.path.join(root, file))

This code successfully finds my file. 此代码成功找到我的文件。 How would I then go about deleting the folder it is in without listing the folder's name. 然后我将如何删除它所在的文件夹而不列出该文件夹的名称。

The answer provided by @BryanOakley was simple. @BryanOakley提供的答案很简单。 The following use of shutil.rmtree(root) solved my problem. 以下对shutil.rmtree(root)解决了我的问题。

import os
import shutil
myfile_path = "H:/PythonTools/test/exampleA"
for root, dirs, files in os.walk(myfile_path):
    for file in files:
        if file.endswith(".cax"):
            shutil.rmtree(root)

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

相关问题 如何使用 Python 删除 Amazon S3 上的文件夹及其内容 - How to delete a folder and its contents on Amazon S3 using Python 如何删除文件夹的内容? - How to delete the contents of a folder? 如何在不删除文件夹的情况下删除文件夹中的内容 python - How to delete the contents within a folder without deleting the folder using python 如何使用boto3删除AWS桶中的文件夹及其内容 - How to delete folder and its content in a AWS bucket using boto3 如何删除文件夹的内容但保留该文件夹? - How can I delete contents of a folder but keep the folder? 如何使用 Python 将文件夹中的 all.txt 文件和 append 其内容读取到 one.txt 文件中? - How to read all .txt files in a folder and append its contents into one .txt file, using Python? 如何在Python 3中从文件夹及其内容导入文件 - How do I import a file from a folder and its contents in Python 3 如何在Python中压缩文件夹及其所有文件,同时保留其内容的文件夹名称和相对路径? - How to zip a folder and all of its files in Python, while preserving the folder name and relative paths for its contents? 将文件夹及其内容复制到Ubuntu中的USB记忆棒 - Copy a folder and its contents to USB stick in Ubuntu Python - 将文件夹及其内容写入ZipFile - Python - Writing a folder and its contents to a ZipFile
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM