Python:如何检查文件夹中的文件夹? [英] Python: How to check folders within folders?
问题描述
首先,如果标题不清楚,我要道歉.
First off, let me apologize if the title is unclear.
为了简化我在工作中要做的任务,我已经开始编写此脚本来自动从特定路径中删除文件.
To simplify a task I do at work, I've started writing this script to automate the removal of files from a certain path.
我的问题是,在当前状态下,此脚本不会检查路径中提供的文件夹中 中文件夹的内容.
My issue is that in its current state, this script does not check the contents of the folders within the folder provided by the path.
我不确定如何解决此问题,因为据我所知,应该正在检查那些文件?
I'm not sure how to fix this, because from what I can tell, it should be checking those files?
import os
def depdelete(path):
for f in os.listdir(path):
if f.endswith('.exe'):
os.remove(os.path.join(path, f))
print('Dep Files have been deleted.')
else:
print('No Dep Files Present.')
def DepInput():
print('Hello, Welcome to DepDelete!')
print('What is the path?')
path = input()
depdelete(path)
DepInput()
推荐答案
尝试使用os.walk
遍历目录树,如下所示:
Try using os.walk
to traverse the directory tree, like this:
def depdelete(path):
for root, _, file_list in os.walk(path):
print("In directory {}".format(root))
for file_name in file_list:
if file_name.endswith(".exe"):
os.remove(os.path.join(root, file_name))
print("Deleted {}".format(os.path.join(root, file_name)))
Here are the docs (there are some usage examples towards the bottom): https://docs.python.org/3/library/os.html#os.walk
这篇关于Python:如何检查文件夹中的文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!