[英]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.